From ef7ef98a495129f7487d4491f2b574b621620bdb Mon Sep 17 00:00:00 2001 From: Tiffany Chio Date: Sun, 15 Sep 2019 14:04:54 -0700 Subject: [PATCH] working remove duplicates and longest prefix --- lib/practice_exercises.rb | 45 ++++++++++++++++++++++++++++----- test/practice_exercises_test.rb | 30 ++++++++++++++-------- 2 files changed, 58 insertions(+), 17 deletions(-) diff --git a/lib/practice_exercises.rb b/lib/practice_exercises.rb index 291e4e6..14c97b0 100644 --- a/lib/practice_exercises.rb +++ b/lib/practice_exercises.rb @@ -1,13 +1,44 @@ -# Time Complexity: ? -# Space Complexity: ? +# Time Complexity: O(n^2) +# Space Complexity: O(1) + def remove_duplicates(list) - raise NotImplementedError, "Not implemented yet" + i = 0 + + while i < list.length + if list[i] == list[i+1] + (i+1..list.length - 1).each do |k| + list[k] = list [k+1] + end + list.pop # for future reference: pop is O(1) + else + i += 1 + end + end + + return list end -# Time Complexity: ? -# Space Complexity: ? +# Time Complexity: O(n) because word lengths are pretty finite, else O(m*n) +# Space Complexity: O(n) def longest_prefix(strings) - raise NotImplementedError, "Not implemented yet" + arr_length = strings.length + word_length = strings[0].length + + result = "" + + word_length.times do |i| + + current_letter = strings[0][i] + + arr_length.times do |j| + if strings[j][i] != current_letter + return result + end + end + + result << current_letter # for future reference: push is O(1) + end + + return result end - diff --git a/test/practice_exercises_test.rb b/test/practice_exercises_test.rb index 11d820b..720b184 100644 --- a/test/practice_exercises_test.rb +++ b/test/practice_exercises_test.rb @@ -9,35 +9,45 @@ it "works for empty arrays" do expect(remove_duplicates([])).must_equal [] end - + it "will remove duplicates for longer arrays" do expect(remove_duplicates([1, 2, 2, 3, 3, 4])).must_equal [1, 2, 3, 4] end + + it "will remove duplicates for even longer arrays" do + expect(remove_duplicates([1, 2, 2, 2, 3, 3, 4, 4, 4, 4])).must_equal [1, 2, 3, 4] + end end - + describe "Longest valid substring" do it "will work for the README strings" do strings = ["flower","flow","flight"] - + output = longest_prefix(strings) - + expect(output).must_equal "fl" end - + it "will work for the strings with the common prefix in the rear" do strings = ["flower","flow","flight", "fpastafl"] - + output = longest_prefix(strings) - + expect(output).must_equal "f" end - + it "will work for the README strings" do strings = ["dog","racecar","car"] - + output = longest_prefix(strings) - + expect(output).must_equal "" end + + it "will work for the flower strings" do + strings = ["flower", "flower", "flower"] + output = longest_prefix(strings) + expect(output).must_equal "flower" + end end end