diff --git a/lib/practice_exercises.rb b/lib/practice_exercises.rb index 291e4e6..a8d6ff9 100644 --- a/lib/practice_exercises.rb +++ b/lib/practice_exercises.rb @@ -1,13 +1,49 @@ +require "pry" +# Time Complexity: o(n) +# Space Complexity: o(1) -# Time Complexity: ? -# Space Complexity: ? +# num = [1, 2, 2, 3, 4, 4] def remove_duplicates(list) - raise NotImplementedError, "Not implemented yet" + i = 0 + while i <= list.length + if list[i] == list[i + 1] + list.delete_at(i) + end + i += 1 + end + + # print list.length + return list end -# Time Complexity: ? -# Space Complexity: ? +# remove_duplicates(num) +#============================================================== + +# Time Complexity: o(n^2) +# Space Complexity: ?o(n) + def longest_prefix(strings) - raise NotImplementedError, "Not implemented yet" -end + total_words = strings.length + prefix = "" + if total_words == 0 + return prefix + end + + if total_words == 1 + return strings[0] + end + + total_words.times do |index| + word = strings[index] + i = index + 1 + while i < total_words + next_word = strings[i] + if prefix[index] != word[index] && word[index] == next_word[index] + prefix += word[index] + end + i += 1 + end + end + return prefix +end diff --git a/test/practice_exercises_test.rb b/test/practice_exercises_test.rb index 4d0bc10..4a9108b 100644 --- a/test/practice_exercises_test.rb +++ b/test/practice_exercises_test.rb @@ -5,19 +5,19 @@ it "works for 1 element strings" do expect(remove_duplicates([1])).must_equal [1] end - + 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]).reject{|num| num == nil }).must_equal [1, 2, 3, 4] + expect(remove_duplicates([1, 2, 2, 3, 3, 4]).reject { |num| num == nil }).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"] + strings = ["flower", "flow", "flight"] output = longest_prefix(strings) @@ -25,7 +25,7 @@ end it "will work for the strings with the common prefix in the rear" do - strings = ["flower","flow","flight", "fpastafl"] + strings = ["flower", "flow", "flight", "fpastafl"] output = longest_prefix(strings) @@ -33,7 +33,7 @@ end it "will work for the README strings" do - strings = ["dog","racecar","car"] + strings = ["dog", "racecar", "car"] output = longest_prefix(strings)