Last active
August 29, 2015 14:25
-
-
Save donigian/acf2250772fc562df2c7 to your computer and use it in GitHub Desktop.
Count duplicates by using only single variable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class InterviewQuestions | |
def initialize(count=0) | |
@count = 0 | |
end | |
def count_duplicates(arr) | |
arr.sort! # your favorite sorting algo (n log n) | |
arr.each_with_index {|index| | |
if (index + 1 < arr.length) | |
if (arr[index+1]==arr[index]) | |
@count +=1 | |
end | |
end | |
} | |
@count | |
end | |
end | |
describe InterviewQuestions do | |
it "should find 0 duplicate numbers for empty array" do | |
InterviewQuestions.new.count_duplicates([ ]).should == 0 | |
end | |
it "should find 0 duplicate numbers for array with single element" do | |
InterviewQuestions.new.count_duplicates([ 1 ]).should == 0 | |
end | |
it "should find 4 duplicate numbers" do | |
InterviewQuestions.new.count_duplicates([3, 1, 5, 9, 3, 2, 1, 1 , 4]).should == 4 | |
end | |
it "should find 2 duplicate numbers for array including (+/-)" do | |
InterviewQuestions.new.count_duplicates([ 5, 1 , -4, -9, -9]).should == 2 | |
end | |
it "should find 0 duplicate numbers" do | |
InterviewQuestions.new.count_duplicates([ 1, 7 , 2, 3, 4]).should == 0 | |
end | |
it "should find 5 duplicate numbers" do | |
InterviewQuestions.new.count_duplicates([ 1, 1, 1, 1, 1 ]).should == 5 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment