diff --git a/DIRECTORY.md b/DIRECTORY.md index 4eb3612..17bbb59 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -14,6 +14,7 @@ * [Get Products Of All Other Elements](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/get_products_of_all_other_elements.rb) * [Remove Elements](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/remove_elements.rb) * [Shuffle Array](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/shuffle_array.rb) + * [Single Number](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/single_number.rb) * [Sort Squares Of An Array](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/sort_squares_of_an_array.rb) * [Two Sum](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/two_sum.rb) * [Two Sum Ii](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/two_sum_ii.rb) diff --git a/data_structures/arrays/single_number.rb b/data_structures/arrays/single_number.rb new file mode 100644 index 0000000..163b7b1 --- /dev/null +++ b/data_structures/arrays/single_number.rb @@ -0,0 +1,61 @@ +# Challenge name: Single Number +# +# Given a non-empty array of integers nums, every element appears twice +# except for one. Find that single one. +# +# Follow up: Could you implement a solution with a linear runtime +# complexity and without using extra memory? +# +# @param {Integer[]} nums +# @return {Integer} + +# +# Approach 1: Hash map +# +# Time Complexity: O(n) +# +def single_number(nums) + result_hash = {} + nums.each do |num| + if result_hash[num] + result_hash[num] +=1 + else + result_hash[num] = 1 + end + end + + result_hash.each do |k, v| + return k if v == 1 + end +end + +nums = [2, 2, 1] +puts(single_number(nums)) +# Output: 1 +nums = [4, 1, 2, 1, 2] +puts(single_number(nums)) +# Output: 4 +nums = [1] +puts(single_number(nums)) +# Output: 1 + +# +# Approach 2: Use Ruby .count() +# +# Time Complexity: O(n^2) +# +def single_number(nums) + nums.find do |num| + nums.count(num) == 1 + end +end + +nums = [2, 2, 1] +puts(single_number(nums)) +# Output: 1 +nums = [4, 1, 2, 1, 2] +puts(single_number(nums)) +# Output: 4 +nums = [1] +puts(single_number(nums)) +# Output: 1 \ No newline at end of file