Skip to content

Solutions in Scala #3001

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
9 changes: 8 additions & 1 deletion scala/0217-contains-duplicate.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,18 @@ import scala.collection.mutable.HashSet

object Solution {
def containsDuplicate(nums: Array[Int]): Boolean = {
var seen: HashSet[Int] = HashSet()
var seen: HashSet[Int] = HashSet()
for (num <- nums) {
if (seen.contains(num)) return true
seen.add(num)
}
return false
}

// using group by and filter
def containDupsOneLiner(nums: Array[Int]): Boolean = {
val dups = nums.groupBy(identity).filter(grps => grps._2.length > 1)
dups.nonEmpty
}

}
20 changes: 20 additions & 0 deletions scala/0238-product-of-array-except-self.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
object Solution {
def productExceptSelf(nums: Array[Int]): Array[Int] = {

val result = Array.fill[Int](nums.length)(1)

var prefix = 1
for(i <- nums.indices) {
result(i) = prefix
prefix = prefix * nums(i)
}

var postfix = 1
for(i <- nums.length-1 to 0 by -1) {
result(i) = result(i) * postfix
postfix = postfix * nums(i)
}

result
}
}
17 changes: 17 additions & 0 deletions scala/0242-valid-anagram.scala
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,21 @@ object Solution {

return true
}

//by maintaing an array of length 26 and using only 1 for loop
def isAnagram2(s: String, t: String): Boolean = {
if(s.length != t.length)
return false

val arr = Array.fill[Int](26)(0)

val idx = (ch: Char) => ch - 'a' // can alternatively be written as: val idx = (_: Char) - 'a'

for (i <- s.indices) {
arr(idx(s(i))) += 1
arr(idx(t(i))) -= 1
}

arr.forall(_ == 0)
}
}
13 changes: 13 additions & 0 deletions scala/0347-top-k-frequent-elements.scala
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,17 @@ object Solution {

map
}

// using `groupBy` and only `one` Mutable Collection.
def topKFrequent2(nums: Array[Int], k: Int): Array[Int] = {

val frequencyArray = Array.fill(nums.length + 1)(ArrayBuffer.empty[Int])

val groupedNums = nums.groupBy(identity).mapValues(_.length)

groupedNums.foreach { case (num, len) => frequencyArray(len) += num }

frequencyArray.flatten.takeRight(k)

}
}