Skip to content

Instantly share code, notes, and snippets.

@donigian
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save donigian/acf2250772fc562df2c7 to your computer and use it in GitHub Desktop.
Save donigian/acf2250772fc562df2c7 to your computer and use it in GitHub Desktop.
Count duplicates by using only single variable
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