Commit b4ea224

mo khan <mo.khan@gmail.com>
2020-08-14 23:01:48
Implment linear time algorithm
1 parent 5ab5e2c
Changed files (1)
2020
08
2020/08/14/main.rb
@@ -0,0 +1,26 @@
+def assert_equals(x, y)
+  raise [x, y].inspect unless x == y
+end
+
+class Solution
+  def self.run(items, target)
+    first = -1
+    last = -1
+
+    for i in (0..target.size)
+      item = items[i]
+      if item == target
+        first = i if first == -1
+        last = i
+      end
+    end
+
+    [first, last]
+  end
+end
+
+assert_equals(Solution.run([1,3,3,5,7,8,9,9,9,15], 9), [6, 8])
+assert_equals(Solution.run([100, 150, 150, 153], 150), [1, 2])
+assert_equals(Solution.run([1,2,3,4,5,6,10], 9), [-1, -1])
+assert_equals(Solution.run([1, 2, 2, 2, 2, 3, 4, 7, 8, 8], 2), [1, 4])
+puts "Yay!"