diff --git a/scala/1-Two-Sum.scala b/scala/1-Two-Sum.scala new file mode 100644 index 000000000..2ea9c3129 --- /dev/null +++ b/scala/1-Two-Sum.scala @@ -0,0 +1,34 @@ +import scala.collection.mutable + +object Solution { + def twoSum(nums: Array[Int], target: Int): Array[Int] = { + val numsWithIndex = nums.zipWithIndex + val targets = numsWithIndex.toMap + + def compliment(v: Int): Option[Int] = targets.get(target - v) + + numsWithIndex + .find { case (v, i) => !compliment(v).forall(_ == i) } + .map { case (v, i) => Array(i, compliment(v).get) } + .orNull + } + + /** + * Optimization of above solution to do it in "one pass" + * i.e. build the map as we traverse the input collection + */ + def twoSumOnePass(nums: Array[Int], target: Int): Array[Int] = { + val targets = mutable.Map[Int, Int]() + + for ((v, i) <- nums.zipWithIndex) { + val answer = targets.get(target - v).map(Array(_, i)) + + if (answer.nonEmpty) + return answer.get + + targets.put(v, i) + } + + null + } +} \ No newline at end of file diff --git a/scala/2-Add-Two-Numbers.scala b/scala/2-Add-Two-Numbers.scala new file mode 100644 index 000000000..6a3d4de75 --- /dev/null +++ b/scala/2-Add-Two-Numbers.scala @@ -0,0 +1,42 @@ +/** + * Definition for singly-linked list. + * class ListNode(_x: Int = 0, _next: ListNode = null) { + * var next: ListNode = _next + * var x: Int = _x + * } + */ +object Solution { + def addTwoNumbers(l1: ListNode, l2: ListNode): ListNode = { + def nonNull(l: ListNode): Boolean = l != null + def next(l: ListNode): ListNode = if (nonNull(l)) l.next else null + def getX(l: ListNode): Int = if (nonNull(l)) l.x else 0 + def sumX(l1: ListNode, l2: ListNode, carry: Int): (ListNode, Int) = { + val sum = getX(l1) + getX(l2) + carry + new ListNode(sum % 10) -> sum / 10 + } + + var carry = 0 + val (sum, newCarry) = sumX(l1, l2, carry) + carry = newCarry + + var nextDigit = sum + var next1 = next(l1) + var next2 = next(l2) + + while (nonNull(next1) || nonNull(next2)) { + val (sum, newCarry) = sumX(next1, next2, carry) + + nextDigit.next = sum + nextDigit = nextDigit.next + + carry = newCarry + next1 = next(next1) + next2 = next(next2) + } + + if (carry > 0) + nextDigit.next = new ListNode(carry) + + sum + } +} diff --git a/scala/3-Longest-Substring-Without-Repeating-Characters.scala b/scala/3-Longest-Substring-Without-Repeating-Characters.scala new file mode 100644 index 000000000..ba7ec453e --- /dev/null +++ b/scala/3-Longest-Substring-Without-Repeating-Characters.scala @@ -0,0 +1,24 @@ +import scala.collection.mutable + +object Solution { + def lengthOfLongestSubstring(s: String): Int = { + val charMap = mutable.Map[Character, Int]() + var longest = 0 + var left = 0 + var right = left + + while (right < s.length) { + if (charMap.get(s(right)).exists(_ >= left)) { + longest = Math.max(longest, right - left) + + left += 1 + } + else { + charMap.put(s(right), right) + right += 1 + } + } + + Math.max(longest, right - left) + } +} \ No newline at end of file