From 4674c2d97b205f14a2b471d00c24afca4e44048f Mon Sep 17 00:00:00 2001 From: Vitor Oliveira Date: Wed, 31 Mar 2021 19:02:57 -0700 Subject: [PATCH 01/50] Valid anagram: hash table approach --- .../arrays/strings/anagram_checker.rb | 2 +- data_structures/hash_table/anagram_checker.rb | 55 +++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) create mode 100644 data_structures/hash_table/anagram_checker.rb diff --git a/data_structures/arrays/strings/anagram_checker.rb b/data_structures/arrays/strings/anagram_checker.rb index bcd5e36..1918b07 100644 --- a/data_structures/arrays/strings/anagram_checker.rb +++ b/data_structures/arrays/strings/anagram_checker.rb @@ -15,7 +15,7 @@ # @return {Boolean} # -# Approach 1: Sort and Compare +# Approach: Sort and Compare # # Complexity analysis: # diff --git a/data_structures/hash_table/anagram_checker.rb b/data_structures/hash_table/anagram_checker.rb new file mode 100644 index 0000000..43163d4 --- /dev/null +++ b/data_structures/hash_table/anagram_checker.rb @@ -0,0 +1,55 @@ +# Challenge name: Is anagram +# +# Given two strings s and t , write a function to determine +# if t is an anagram of s. +# +# Note: +# You may assume the string contains only lowercase alphabets. +# +# Follow up: +# What if the inputs contain unicode characters? +# How would you adapt your solution to such case? +# +# @param {String} s +# @param {String} t +# @return {Boolean} + +# +# Approach: Hash table +# +# Complexity analysis: +# +# Time complexity: O(n). Time complexity is O(n) since accessing the counter table is a constant time operation. +# Space complexity: O(1). Although we do use extra space, the space complexity is O(1) because the table's size stays constant no matter how large n is. +# +def is_anagram(s, t) + s_length = s.length + t_length = t.length + counter = Hash.new(0) + + return false unless s_length == t_length + + (0...s_length).each do |i| + counter[s[i]] += 1 + counter[t[i]] -= 1 + end + + counter.each do |k, v| + return false unless v == 0 + end + + true +end + +s = 'anagram' +t = 'nagaram' +puts(is_anagram(s, t)) +# => true +s = 'rat' +t = 'car' +puts(is_anagram(s, t)) +# => false +s = 'a' +t = 'ab' +puts(is_anagram(s, t)) +# => false From 2da2ec55f6e32b1c418e44c6b2a4576ecfbfb54f Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Thu, 1 Apr 2021 02:03:14 +0000 Subject: [PATCH 02/50] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index d0c4469..42b9add 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -32,6 +32,7 @@ * [Postorder Traversal](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/binary_trees/postorder_traversal.rb) * [Preorder Traversal](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/binary_trees/preorder_traversal.rb) * Hash Table + * [Anagram Checker](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/hash_table/anagram_checker.rb) * [Find All Duplicates In An Array](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/hash_table/find_all_duplicates_in_an_array.rb) * [Richest Customer Wealth](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/hash_table/richest_customer_wealth.rb) * [Two Sum](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/hash_table/two_sum.rb) From ad959fcfb037a205a42bfed1b496624e2faa05ad Mon Sep 17 00:00:00 2001 From: Vitor Oliveira Date: Wed, 31 Mar 2021 19:04:39 -0700 Subject: [PATCH 03/50] Minor changes --- data_structures/hash_table/anagram_checker.rb | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/data_structures/hash_table/anagram_checker.rb b/data_structures/hash_table/anagram_checker.rb index 43163d4..03f72fa 100644 --- a/data_structures/hash_table/anagram_checker.rb +++ b/data_structures/hash_table/anagram_checker.rb @@ -19,8 +19,11 @@ # # Complexity analysis: # -# Time complexity: O(n). Time complexity is O(n) since accessing the counter table is a constant time operation. -# Space complexity: O(1). Although we do use extra space, the space complexity is O(1) because the table's size stays constant no matter how large n is. +# Time complexity: O(n). Time complexity is O(n) since accessing the counter +# table is a constant time operation. +# Space complexity: O(1). Although we do use extra space, +# the space complexity is O(1) because the table's size stays constant no +# matter how large n is. # def is_anagram(s, t) s_length = s.length @@ -45,10 +48,12 @@ s = 'anagram' t = 'nagaram' puts(is_anagram(s, t)) # => true + s = 'rat' t = 'car' puts(is_anagram(s, t)) # => false + s = 'a' t = 'ab' puts(is_anagram(s, t)) From 6b8529a1a698e7316cb809fd01c557f6b7726142 Mon Sep 17 00:00:00 2001 From: Vitor Oliveira Date: Wed, 31 Mar 2021 19:05:51 -0700 Subject: [PATCH 04/50] Update anagram_checker.rb --- data_structures/hash_table/anagram_checker.rb | 2 ++ 1 file changed, 2 insertions(+) diff --git a/data_structures/hash_table/anagram_checker.rb b/data_structures/hash_table/anagram_checker.rb index 03f72fa..1158134 100644 --- a/data_structures/hash_table/anagram_checker.rb +++ b/data_structures/hash_table/anagram_checker.rb @@ -17,6 +17,8 @@ # # Approach: Hash table # + +# # Complexity analysis: # # Time complexity: O(n). Time complexity is O(n) since accessing the counter From dc533283a2a3c5743fae1548210f8968fb7a8d08 Mon Sep 17 00:00:00 2001 From: Vitor Oliveira Date: Thu, 1 Apr 2021 09:36:46 -0700 Subject: [PATCH 05/50] Add hash table approach --- data_structures/hash_table/anagram_checker.rb | 73 ++++++++++++++++++- 1 file changed, 71 insertions(+), 2 deletions(-) diff --git a/data_structures/hash_table/anagram_checker.rb b/data_structures/hash_table/anagram_checker.rb index 1158134..0d0f2f6 100644 --- a/data_structures/hash_table/anagram_checker.rb +++ b/data_structures/hash_table/anagram_checker.rb @@ -17,8 +17,6 @@ # # Approach: Hash table # - -# # Complexity analysis: # # Time complexity: O(n). Time complexity is O(n) since accessing the counter @@ -60,3 +58,74 @@ s = 'a' t = 'ab' puts(is_anagram(s, t)) # => false + + +def is_anagram(s, t) + s_length = s.length + t_length = t.length + counter = Hash.new(0) + + return false unless s_length == t_length + + (0...s_length).each do |i| + counter[s[i]] += 1 + end + + (0...s_length).each do |i| + counter[t[i]] -= 1 + + return false if counter[t[i]] < 0 + end + + true +end + +s = 'anagram' +t = 'nagaram' +puts(is_anagram(s, t)) +# => true + +s = 'rat' +t = 'car' +puts(is_anagram(s, t)) +# => false + +s = 'a' +t = 'ab' +puts(is_anagram(s, t)) +# => false + +# +# Approach 2: Hash table +# + +# Algorithm: we could also first increment the counter for s, +# then decrement the counter for t. If at any point the counter +# drops below zero, we know that t contains an extra letter, +# not in s, and return false immediately. + +# Complexity analysis: +# +# Time complexity: O(n). +# Space complexity: O(1). +# + +def is_anagram(s, t) + s_length = s.length + t_length = t.length + counter = Hash.new(0) + + return false unless s_length == t_length + + (0...s_length).each do |i| + counter[s[i]] += 1 + end + + (0...s_length).each do |i| + counter[t[i]] -= 1 + + return false if counter[t[i]] < 0 + end + + true +end From 44c32084541b2679161577a1257d1454d4f4752d Mon Sep 17 00:00:00 2001 From: Vitor Oliveira Date: Thu, 1 Apr 2021 09:36:52 -0700 Subject: [PATCH 06/50] Add another hash table approach --- data_structures/hash_table/anagram_checker.rb | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/data_structures/hash_table/anagram_checker.rb b/data_structures/hash_table/anagram_checker.rb index 0d0f2f6..16fc429 100644 --- a/data_structures/hash_table/anagram_checker.rb +++ b/data_structures/hash_table/anagram_checker.rb @@ -129,3 +129,38 @@ def is_anagram(s, t) true end + +# +# Approach 3: populate 2 hashes and compare them +# + +def is_anagram(s, t) + s = s.chars + t = t.chars + + return false if s.count != t.count + + hash1 = {} + s.chars.each do |value| + hash1[value] = if hash1[value] + hash1[value] + 1 + else + 1 + end + end + + hash2 = {} + t.chars.each do |value| + hash2[value] = if hash2[value] + hash2[value] + 1 + else + 1 + end + end + + hash1.keys.each do |key| + return false if hash2[key] != hash1[key] + end + + true +end From 434e72a4f7cc0cd977e98c941449e492929e1d2f Mon Sep 17 00:00:00 2001 From: Vitor Oliveira Date: Thu, 1 Apr 2021 09:38:27 -0700 Subject: [PATCH 07/50] Add very simple tests --- data_structures/hash_table/anagram_checker.rb | 34 +++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/data_structures/hash_table/anagram_checker.rb b/data_structures/hash_table/anagram_checker.rb index 16fc429..abbb209 100644 --- a/data_structures/hash_table/anagram_checker.rb +++ b/data_structures/hash_table/anagram_checker.rb @@ -130,6 +130,21 @@ def is_anagram(s, t) true end +s = 'anagram' +t = 'nagaram' +puts(is_anagram(s, t)) +# => true + +s = 'rat' +t = 'car' +puts(is_anagram(s, t)) +# => false + +s = 'a' +t = 'ab' +puts(is_anagram(s, t)) +# => false + # # Approach 3: populate 2 hashes and compare them # @@ -141,7 +156,7 @@ def is_anagram(s, t) return false if s.count != t.count hash1 = {} - s.chars.each do |value| + s.each do |value| hash1[value] = if hash1[value] hash1[value] + 1 else @@ -150,7 +165,7 @@ def is_anagram(s, t) end hash2 = {} - t.chars.each do |value| + t.each do |value| hash2[value] = if hash2[value] hash2[value] + 1 else @@ -164,3 +179,18 @@ def is_anagram(s, t) true end + +s = 'anagram' +t = 'nagaram' +puts(is_anagram(s, t)) +# => true + +s = 'rat' +t = 'car' +puts(is_anagram(s, t)) +# => false + +s = 'a' +t = 'ab' +puts(is_anagram(s, t)) +# => false From 515b076e61872aaeac08d09ad6c77007ce1d75d5 Mon Sep 17 00:00:00 2001 From: Vitor Oliveira Date: Thu, 1 Apr 2021 09:42:45 -0700 Subject: [PATCH 08/50] remove duplication --- data_structures/hash_table/anagram_checker.rb | 37 +------------------ 1 file changed, 1 insertion(+), 36 deletions(-) diff --git a/data_structures/hash_table/anagram_checker.rb b/data_structures/hash_table/anagram_checker.rb index abbb209..e15eed4 100644 --- a/data_structures/hash_table/anagram_checker.rb +++ b/data_structures/hash_table/anagram_checker.rb @@ -17,6 +17,7 @@ # # Approach: Hash table # + # Complexity analysis: # # Time complexity: O(n). Time complexity is O(n) since accessing the counter @@ -59,42 +60,6 @@ t = 'ab' puts(is_anagram(s, t)) # => false - -def is_anagram(s, t) - s_length = s.length - t_length = t.length - counter = Hash.new(0) - - return false unless s_length == t_length - - (0...s_length).each do |i| - counter[s[i]] += 1 - end - - (0...s_length).each do |i| - counter[t[i]] -= 1 - - return false if counter[t[i]] < 0 - end - - true -end - -s = 'anagram' -t = 'nagaram' -puts(is_anagram(s, t)) -# => true - -s = 'rat' -t = 'car' -puts(is_anagram(s, t)) -# => false - -s = 'a' -t = 'ab' -puts(is_anagram(s, t)) -# => false - # # Approach 2: Hash table # From c2bd60c2231b3ccbc385a4dd46d3e7ead10aab9b Mon Sep 17 00:00:00 2001 From: Jessica Kwok Date: Thu, 1 Apr 2021 09:31:12 -0700 Subject: [PATCH 09/50] Add palindrome challenge --- DIRECTORY.md | 1 + data_structures/arrays/strings/palindrome.rb | 44 ++++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 data_structures/arrays/strings/palindrome.rb diff --git a/DIRECTORY.md b/DIRECTORY.md index d0c4469..bca02fb 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -23,6 +23,7 @@ * Strings * [Anagram Checker](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/strings/anagram_checker.rb) * [Jewels And Stones](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/strings/jewels_and_stones.rb) + * [Palindrome](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/strings/palindrome.rb) * [Remove Vowels](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/strings/remove_vowels.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/strings/palindrome.rb b/data_structures/arrays/strings/palindrome.rb new file mode 100644 index 0000000..1ebcfbe --- /dev/null +++ b/data_structures/arrays/strings/palindrome.rb @@ -0,0 +1,44 @@ +# Challenge name: Valid Palindrome +# +# Given a string s, determine if it is a palindrome, +# considering only alphanumeric characters and ignoring cases. +# +# Example 1: +# Input: s = "A man, a plan, a canal: Panama" +# Output: true +# Explanation: "amanaplanacanalpanama" is a palindrome. +# +# Example 2: +# Input: s = "race a car" +# Output: false +# Explanation: "raceacar" is not a palindrome. +# +# Constraints: +# 1 <= s.length <= 2 * 105 +# s consists only of printable ASCII characters. +# @param {String} s +# @return {Boolean} + +# +# Approach 1: Brute Force +# +# Time Complexity: +# +def is_palindrome(s) + s.downcase +end + +s = 'A man, a plan, a canal: Panama' +puts is_palindrome(s) +# Output: true +# Explanation: "amanaplanacanalpanama" is a palindrome. + +s = 'race a car' +puts is_palindrome(s) +# Output: false +# Explanation: "raceacar" is not a palindrome. + +s = 'ab_a' +puts is_palindrome(s) +# Output: true +# Explanation: "aba" is a palindrome. \ No newline at end of file From 13aec345eaca265cc5ea218754faefc62fe557a6 Mon Sep 17 00:00:00 2001 From: Vitor Oliveira Date: Thu, 1 Apr 2021 09:54:34 -0700 Subject: [PATCH 10/50] add generate_parenthesis backtracking approach --- backtracking/generate_paranthesis.rb | 47 ++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 backtracking/generate_paranthesis.rb diff --git a/backtracking/generate_paranthesis.rb b/backtracking/generate_paranthesis.rb new file mode 100644 index 0000000..5881aea --- /dev/null +++ b/backtracking/generate_paranthesis.rb @@ -0,0 +1,47 @@ +# Given n pairs of parentheses, write a function to generate all combinations +# of well-formed parentheses. +# +# Example 1: +# +# Input: n = 3 +# Output: ["((()))","(()())","(())()","()(())","()()()"] +# Example 2: +# +# Input: n = 1 +# Output: ["()"] +# +# +# Constraints: +# +# 1 <= n <= 8 + +# @param {Integer} n +# @return {String[]} +def generate_parenthesis(n) + parenthesis = [] + backtrack(parenthesis, "", 0, 0, n) + parenthesis +end + +def backtrack(parenthesis, curr, open, close, max) + if curr.length == max * 2 + parenthesis.push(curr) + return + end + + if open < max + backtrack(parenthesis, curr + "(", open + 1, close, max) + end + + if close < open + backtrack(parenthesis, curr + ")", open, close + 1, max) + end +end + +n = 3 +print(generate_parenthesis(n)) +# Output: ["((()))","(()())","(())()","()(())","()()()"] + +n = 1 +print(generate_parenthesis(n)) +# Output: ["()"] From 1350b46474aa437169639166e041ebdfdaa469af Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Thu, 1 Apr 2021 16:54:50 +0000 Subject: [PATCH 11/50] updating DIRECTORY.md --- DIRECTORY.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 42b9add..7c86a15 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -1,4 +1,7 @@ +## Backtracking + * [Generate Paranthesis](https://github.com/TheAlgorithms/Ruby/blob/master/backtracking/generate_paranthesis.rb) + ## Bit Manipulation * [Power Of Two](https://github.com/TheAlgorithms/Ruby/blob/master/bit_manipulation/power_of_two.rb) From 1d974b2ea18e646fe277ada716902d42ed95c659 Mon Sep 17 00:00:00 2001 From: Vitor Oliveira Date: Thu, 1 Apr 2021 09:58:04 -0700 Subject: [PATCH 12/50] Add approach description --- backtracking/generate_paranthesis.rb | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/backtracking/generate_paranthesis.rb b/backtracking/generate_paranthesis.rb index 5881aea..587a25c 100644 --- a/backtracking/generate_paranthesis.rb +++ b/backtracking/generate_paranthesis.rb @@ -15,6 +15,16 @@ # # 1 <= n <= 8 +# Approach: +# +# Let's only add '(' or ')' when we know it will remain a valid sequence. +# We can do this by keeping track of the number of opening and closing brackets +# we have placed so far. +# +# We can start an opening bracket if we still have one (of n) left to place. +# And we could start a closing bracket if it'd not exceed the number of opening +# brackets. + # @param {Integer} n # @return {String[]} def generate_parenthesis(n) From 7eea20ed6e0369db5d5ff8d2f99aa431ac78a224 Mon Sep 17 00:00:00 2001 From: Vitor Oliveira Date: Thu, 1 Apr 2021 10:06:40 -0700 Subject: [PATCH 13/50] Add complexity analysis and detailed example --- backtracking/generate_paranthesis.rb | 49 ++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/backtracking/generate_paranthesis.rb b/backtracking/generate_paranthesis.rb index 587a25c..0ea684e 100644 --- a/backtracking/generate_paranthesis.rb +++ b/backtracking/generate_paranthesis.rb @@ -25,6 +25,14 @@ # And we could start a closing bracket if it'd not exceed the number of opening # brackets. +# Complexity Analysis +# +# Time Complexity: O(4^n/sqrt(n). Each valid sequence has at most n steps during the backtracking procedure. +# Space Complexity: O(4^n/sqrt(n), as described above, and using O(n) space to store the sequence. + +# Refer to the attached diagram for recursion, +# The numbers next to each node are the counts of left and right parantheses + # @param {Integer} n # @return {String[]} def generate_parenthesis(n) @@ -52,6 +60,47 @@ n = 3 print(generate_parenthesis(n)) # Output: ["((()))","(()())","(())()","()(())","()()()"] +# *** Example: n = 3 *** Space after each DFS instance +# backtrack called with 0 0 [] +# backtrack called with ( 1 0 [] +# backtrack called with (( 2 0 [] +# backtrack called with ((( 3 0 [] +# backtrack called with ((() 3 1 [] +# backtrack called with ((()) 3 2 [] +# backtrack called with ((())) 3 3 [] +# backtrack return with ((()) 3 2 ["((()))"] +# backtrack return with ((() 3 1 ["((()))"] +# backtrack return with ((( 3 0 ["((()))"] +# backtrack called with (() 2 1 ["((()))"] +# backtrack called with (()( 3 1 ["((()))"] +# backtrack called with (()() 3 2 ["((()))"] +# backtrack called with (()()) 3 3 ["((()))"] +# backtrack return with (()() 3 2 ["((()))", "(()())"] +# backtrack return with (()( 3 1 ["((()))", "(()())"] +# backtrack called with (()) 2 2 ["((()))", "(()())"] +# backtrack called with (())( 3 2 ["((()))", "(()())"] +# backtrack called with (())() 3 3 ["((()))", "(()())"] +# backtrack return with (())( 3 2 ["((()))", "(()())", "(())()"] +# backtrack return with (()) 2 2 ["((()))", "(()())", "(())()"] +# backtrack return with (() 2 1 ["((()))", "(()())", "(())()"] +# backtrack return with (( 2 0 ["((()))", "(()())", "(())()"] +# backtrack called with () 1 1 ["((()))", "(()())", "(())()"] +# backtrack called with ()( 2 1 ["((()))", "(()())", "(())()"] +# backtrack called with ()(( 3 1 ["((()))", "(()())", "(())()"] +# backtrack called with ()(() 3 2 ["((()))", "(()())", "(())()"] +# backtrack called with ()(()) 3 3 ["((()))", "(()())", "(())()"] +# backtrack return with ()(() 3 2 ["((()))", "(()())", "(())()", "()(())"] +# backtrack return with ()(( 3 1 ["((()))", "(()())", "(())()", "()(())"] +# backtrack called with ()() 2 2 ["((()))", "(()())", "(())()", "()(())"] +# backtrack called with ()()( 3 2 ["((()))", "(()())", "(())()", "()(())"] +# backtrack called with ()()() 3 3 ["((()))", "(()())", "(())()", "()(())"] +# backtrack return with ()()( 3 2 ["((()))", "(()())", "(())()", "()(())", "()()()"] +# backtrack return with ()() 2 2 ["((()))", "(()())", "(())()", "()(())", "()()()"] +# backtrack return with ()( 2 1 ["((()))", "(()())", "(())()", "()(())", "()()()"] +# backtrack return with () 1 1 ["((()))", "(()())", "(())()", "()(())", "()()()"] +# backtrack return with ( 1 0 ["((()))", "(()())", "(())()", "()(())", "()()()"] +# backtrack return with 0 0 ["((()))", "(()())", "(())()", "()(())", "()()()"] + n = 1 print(generate_parenthesis(n)) # Output: ["()"] From fc0c664f6bd123fd2e6f5dba7a06c05497240866 Mon Sep 17 00:00:00 2001 From: Vitor Oliveira Date: Thu, 1 Apr 2021 10:45:41 -0700 Subject: [PATCH 14/50] close ) --- backtracking/generate_paranthesis.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/backtracking/generate_paranthesis.rb b/backtracking/generate_paranthesis.rb index 0ea684e..5c0e3fa 100644 --- a/backtracking/generate_paranthesis.rb +++ b/backtracking/generate_paranthesis.rb @@ -27,8 +27,8 @@ # Complexity Analysis # -# Time Complexity: O(4^n/sqrt(n). Each valid sequence has at most n steps during the backtracking procedure. -# Space Complexity: O(4^n/sqrt(n), as described above, and using O(n) space to store the sequence. +# Time Complexity: O(4^n/sqrt(n)). Each valid sequence has at most n steps during the backtracking procedure. +# Space Complexity: O(4^n/sqrt(n)), as described above, and using O(n) space to store the sequence. # Refer to the attached diagram for recursion, # The numbers next to each node are the counts of left and right parantheses From e90238e1f712285bb87d421acdb34de0760d8ef5 Mon Sep 17 00:00:00 2001 From: Abhinav Anand Date: Fri, 2 Apr 2021 23:01:29 +0530 Subject: [PATCH 15/50] Added factorial iterative program --- maths/factorial_iterative.rb | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 maths/factorial_iterative.rb diff --git a/maths/factorial_iterative.rb b/maths/factorial_iterative.rb new file mode 100644 index 0000000..cc070b3 --- /dev/null +++ b/maths/factorial_iterative.rb @@ -0,0 +1,28 @@ +=begin +A ruby program calculate factorial of a given number. +Mathematical Explanation: The factorial of a number is the product of all the integers from 1 to that number. +i.e: n! = n*(n-1)*(n-2)......*2*1 +=end + +def factorial(n) + if n < 0 + return nil + end + + fac = 1 + while n > 0 + fac = fac * n + n -= 1 + end + + return fac +end + +puts '4! = ' + factorial(4).to_s +# 4! = 24 + +puts '0! = ' + factorial(0).to_s +# 0! = 1 + +puts '10! = ' + factorial(10).to_s +# 10! = 3628800 From 30c9176098283561bee7598eaaebe3019bd345cd Mon Sep 17 00:00:00 2001 From: Vitor Oliveira Date: Fri, 2 Apr 2021 11:22:53 -0700 Subject: [PATCH 16/50] minor changes --- .../{factorial_iterative.rb => factorial.rb} | 25 +++++++++++-------- 1 file changed, 14 insertions(+), 11 deletions(-) rename maths/{factorial_iterative.rb => factorial.rb} (72%) diff --git a/maths/factorial_iterative.rb b/maths/factorial.rb similarity index 72% rename from maths/factorial_iterative.rb rename to maths/factorial.rb index cc070b3..e83b347 100644 --- a/maths/factorial_iterative.rb +++ b/maths/factorial.rb @@ -4,18 +4,21 @@ Mathematical Explanation: The factorial of a number is the product of all the in i.e: n! = n*(n-1)*(n-2)......*2*1 =end +# +# Approach: Interative +# + def factorial(n) - if n < 0 - return nil - end - - fac = 1 - while n > 0 - fac = fac * n - n -= 1 - end - - return fac + return nil if n < 0 + + fac = 1 + + while n > 0 + fac *= n + n -= 1 + end + + fac end puts '4! = ' + factorial(4).to_s From 46ec0d4fecc019582272ee848f6be2659abd9d21 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Fri, 2 Apr 2021 18:23:23 +0000 Subject: [PATCH 17/50] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 42b9add..b732e81 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -66,6 +66,7 @@ * [Ceil](https://github.com/TheAlgorithms/Ruby/blob/master/maths/ceil.rb) * [Ceil Test](https://github.com/TheAlgorithms/Ruby/blob/master/maths/ceil_test.rb) * [Decimal To Binary](https://github.com/TheAlgorithms/Ruby/blob/master/maths/decimal_to_binary.rb) + * [Factorial](https://github.com/TheAlgorithms/Ruby/blob/master/maths/factorial.rb) * [Fibonacci](https://github.com/TheAlgorithms/Ruby/blob/master/maths/fibonacci.rb) * [Number Of Digits](https://github.com/TheAlgorithms/Ruby/blob/master/maths/number_of_digits.rb) * [Power Of Two](https://github.com/TheAlgorithms/Ruby/blob/master/maths/power_of_two.rb) From b1b6f80a0bf16781f828027437c55c6404eaf031 Mon Sep 17 00:00:00 2001 From: Sahil Afrid Farookhi Date: Sun, 4 Apr 2021 18:26:00 +0530 Subject: [PATCH 18/50] average mean ruby program implementation --- maths/average_mean.rb | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 maths/average_mean.rb diff --git a/maths/average_mean.rb b/maths/average_mean.rb new file mode 100644 index 0000000..0efd5d0 --- /dev/null +++ b/maths/average_mean.rb @@ -0,0 +1,28 @@ +# A ruby program for finding average mean + +module AverageMean + # Average mean = sum of elements / total number of elements + def self.average_mean(n, *array) + if n.instance_of? Integer + if n == array.size + puts "The average mean of the following elements #{array} is #{array.sum/array.size}." + else + puts "Provide the required #{n} elements properly!" + end + else + raise + end + rescue + puts "Error: Please provide number only!" + end +end + +# Valid inputs +AverageMean.average_mean(2, 3, 1) +AverageMean.average_mean(5, 1, 2, 3, 4, 5) +AverageMean.average_mean(3, 2, 2, 2) + +# Invalid inputs +AverageMean.average_mean(2, 3, 1, 5) +AverageMean.average_mean(2, 3, "a") +AverageMean.average_mean("a", 1, 2) From 04a4c9aaedfac2f3b9145be39f1201362a053a0d Mon Sep 17 00:00:00 2001 From: Jessica Kwok Date: Mon, 5 Apr 2021 13:57:41 -0700 Subject: [PATCH 19/50] Add solution using .reverse --- data_structures/arrays/strings/palindrome.rb | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/data_structures/arrays/strings/palindrome.rb b/data_structures/arrays/strings/palindrome.rb index 1ebcfbe..03490ac 100644 --- a/data_structures/arrays/strings/palindrome.rb +++ b/data_structures/arrays/strings/palindrome.rb @@ -20,12 +20,13 @@ # @return {Boolean} # -# Approach 1: Brute Force +# Approach 1: Using Ruby method .reverse # -# Time Complexity: +# Time Complexity: O(n) # def is_palindrome(s) - s.downcase + letters_only = s.downcase.gsub(/[^0-9a-z]/i, '') + letters_only.reverse == letters_only end s = 'A man, a plan, a canal: Panama' From 6c7b37ab76b1a52c93205d91fb65a9d0413cc1db Mon Sep 17 00:00:00 2001 From: Jessica Kwok Date: Mon, 5 Apr 2021 14:08:23 -0700 Subject: [PATCH 20/50] Add solution using a reversed array --- data_structures/arrays/strings/palindrome.rb | 29 ++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/data_structures/arrays/strings/palindrome.rb b/data_structures/arrays/strings/palindrome.rb index 03490ac..4d70171 100644 --- a/data_structures/arrays/strings/palindrome.rb +++ b/data_structures/arrays/strings/palindrome.rb @@ -39,6 +39,35 @@ puts is_palindrome(s) # Output: false # Explanation: "raceacar" is not a palindrome. +s = 'ab_a' +puts is_palindrome(s) +# Output: true +# Explanation: "aba" is a palindrome. + +# +# Approach 2: Reversed array +# +# Time Complexity: O(n) +# +def is_palindrome(s) + letters_only_array = s.downcase.gsub(/[^0-9a-z]/i, '').split('') + reversed_array = [] + letters_only_array.each do |letter| + reversed_array.unshift(letter) + end + letters_only_array == reversed_array +end + +s = 'A man, a plan, a canal: Panama' +puts is_palindrome(s) +# Output: true +# Explanation: "amanaplanacanalpanama" is a palindrome. + +s = 'race a car' +puts is_palindrome(s) +# Output: false +# Explanation: "raceacar" is not a palindrome. + s = 'ab_a' puts is_palindrome(s) # Output: true From 7655003b6cc333ee1512a33f7c9fa0901974189d Mon Sep 17 00:00:00 2001 From: Jessica Kwok Date: Mon, 5 Apr 2021 14:31:57 -0700 Subject: [PATCH 21/50] Add solution using two pointers --- data_structures/arrays/strings/palindrome.rb | 36 ++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/data_structures/arrays/strings/palindrome.rb b/data_structures/arrays/strings/palindrome.rb index 4d70171..28e7921 100644 --- a/data_structures/arrays/strings/palindrome.rb +++ b/data_structures/arrays/strings/palindrome.rb @@ -68,6 +68,42 @@ puts is_palindrome(s) # Output: false # Explanation: "raceacar" is not a palindrome. +s = 'ab_a' +puts is_palindrome(s) +# Output: true +# Explanation: "aba" is a palindrome. + +# +# Approach 2: Two Pointers +# +# Time Complexity: O(n) +# +def is_palindrome(s) + letters_only = s.downcase.gsub(/[^0-9a-z]/i, '') + p1 = 0 + p2 = letters_only.length - 1 + + while p1 < p2 + if letters_only[p1] == letters_only[p2] + p1 += 1 + p2 -= 1 + else + return false + end + end + true +end + +s = 'A man, a plan, a canal: Panama' +puts is_palindrome(s) +# Output: true +# Explanation: "amanaplanacanalpanama" is a palindrome. + +s = 'race a car' +puts is_palindrome(s) +# Output: false +# Explanation: "raceacar" is not a palindrome. + s = 'ab_a' puts is_palindrome(s) # Output: true From e6b674275ea56995dafe8e7e080e3789ea503f91 Mon Sep 17 00:00:00 2001 From: nyapsilon Date: Fri, 9 Apr 2021 21:24:04 +0300 Subject: [PATCH 22/50] Minor code style improvements Tabs are corrected, semantic blocks are separated. --- Searches/binary_search.rb | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/Searches/binary_search.rb b/Searches/binary_search.rb index bbc8efa..d0710a2 100644 --- a/Searches/binary_search.rb +++ b/Searches/binary_search.rb @@ -8,18 +8,21 @@ def binary_search(array, key) return middle if array[middle] == key if key < array[middle] - back = middle - 1 -else - front = middle + 1 -end + back = middle - 1 + else + front = middle + 1 + end end + nil end puts "Enter a sorted space-separated list:" arr = gets.chomp.split(' ').map(&:to_i) + puts "Enter the value to be searched:" value = gets.chomp.to_i + puts if binary_search(arr, value) != nil "Found at index #{binary_search(arr, value)}" else From bd6b1067c0b56d206e7c4a9307c57312289bc197 Mon Sep 17 00:00:00 2001 From: Vitor Oliveira Date: Fri, 9 Apr 2021 21:07:54 -0700 Subject: [PATCH 23/50] Update data_structures/arrays/strings/palindrome.rb --- data_structures/arrays/strings/palindrome.rb | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/data_structures/arrays/strings/palindrome.rb b/data_structures/arrays/strings/palindrome.rb index 28e7921..176243e 100644 --- a/data_structures/arrays/strings/palindrome.rb +++ b/data_structures/arrays/strings/palindrome.rb @@ -76,7 +76,14 @@ puts is_palindrome(s) # # Approach 2: Two Pointers # -# Time Complexity: O(n) + +# +# Complexity Analysis: +# +# Time Complexity: O(n), in length n of the string. We traverse over each +# character at most once until the two pointers meet in the middle, or when +# we break and return early. +# Space Complexity: O(1). No extra space required, at all. # def is_palindrome(s) letters_only = s.downcase.gsub(/[^0-9a-z]/i, '') @@ -107,4 +114,4 @@ puts is_palindrome(s) s = 'ab_a' puts is_palindrome(s) # Output: true -# Explanation: "aba" is a palindrome. \ No newline at end of file +# Explanation: "aba" is a palindrome. From 49db26c56be44d2ca3ab00034e264a1ae877604e Mon Sep 17 00:00:00 2001 From: Vitor Oliveira Date: Fri, 9 Apr 2021 21:07:57 -0700 Subject: [PATCH 24/50] Update data_structures/arrays/strings/palindrome.rb --- data_structures/arrays/strings/palindrome.rb | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/data_structures/arrays/strings/palindrome.rb b/data_structures/arrays/strings/palindrome.rb index 176243e..587e242 100644 --- a/data_structures/arrays/strings/palindrome.rb +++ b/data_structures/arrays/strings/palindrome.rb @@ -47,7 +47,17 @@ puts is_palindrome(s) # # Approach 2: Reversed array # -# Time Complexity: O(n) +# Complexity Analysis: +# +# Time Complexity: O(n), in length n of the string. +# +# We need to iterate through the string: When we filter out non-alphanumeric characters and convert the remaining +# characters to lower-case. When we reverse the string. When we compare the original and the reversed strings. +# Each iteration runs linearly in time (since each character operation completes in constant time). +# Thus, the effective run-time complexity is linear. +# +# Space Complexity: O(n), in length n of the string. We need O(n) additional +# space to store the filtered string and the reversed string. # def is_palindrome(s) letters_only_array = s.downcase.gsub(/[^0-9a-z]/i, '').split('') From 443cf9db8850e78d45f1fde83907f1d021e597e0 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 10 Apr 2021 04:07:57 +0000 Subject: [PATCH 25/50] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index d118dca..c94db91 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -65,6 +65,7 @@ * [Add Digits](https://github.com/TheAlgorithms/Ruby/blob/master/maths/add_digits.rb) * [Aliquot Sum](https://github.com/TheAlgorithms/Ruby/blob/master/maths/aliquot_sum.rb) * [Aliquot Sum Test](https://github.com/TheAlgorithms/Ruby/blob/master/maths/aliquot_sum_test.rb) + * [Average Mean](https://github.com/TheAlgorithms/Ruby/blob/master/maths/average_mean.rb) * [Binary To Decimal](https://github.com/TheAlgorithms/Ruby/blob/master/maths/binary_to_decimal.rb) * [Ceil](https://github.com/TheAlgorithms/Ruby/blob/master/maths/ceil.rb) * [Ceil Test](https://github.com/TheAlgorithms/Ruby/blob/master/maths/ceil_test.rb) From 9fbd75fa66dd64a7766fa250075e37bcd26c406f Mon Sep 17 00:00:00 2001 From: Vitor Oliveira Date: Sat, 10 Apr 2021 09:56:05 -0700 Subject: [PATCH 26/50] Add hash table approach --- data_structures/arrays/arrays_intersection.rb | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 data_structures/arrays/arrays_intersection.rb diff --git a/data_structures/arrays/arrays_intersection.rb b/data_structures/arrays/arrays_intersection.rb new file mode 100644 index 0000000..cf1c1dc --- /dev/null +++ b/data_structures/arrays/arrays_intersection.rb @@ -0,0 +1,55 @@ +# Given three integer arrays arr1, arr2 and arr3 sorted in strictly increasing order, return a sorted array of only the integers that appeared in all three arrays. +# +# Example 1: +# +# Input: arr1 = [1,2,3,4,5], arr2 = [1,2,5,7,9], arr3 = [1,3,4,5,8] +# Output: [1,5] +# Explanation: Only 1 and 5 appeared in the three arrays. +# +# Example 2: +# +# Input: arr1 = [197,418,523,876,1356], arr2 = [501,880,1593,1710,1870], arr3 = [521,682,1337,1395,1764] +# Output: [] +# +# + +# +# Approach: Hash table +# + +# Complexity Analysis + +# Time Complexity: O(n) - n is the total length of +# all of the input arrays. +# Space Complexity: O(n) - n is the total length of all of the +# input arrays. This is because we adopted a Hash table to store all +# numbers and their number of appearances as values. + +def arrays_intersection(arr1, arr2, arr3) + hash = Hash.new(0) + + add_to_hash(arr1, hash) + add_to_hash(arr2, hash) + add_to_hash(arr3, hash) + + hash.select { |key, value| value == 3 }.keys +end + +def add_to_hash(arr, hash) + arr.each_with_index do |value, index| + hash[value] += 1 + end +end + +arr1 = [1,2,3,4,5] +arr2 = [1,2,5,7,9] +arr3 = [1,3,4,5,8] +print arrays_intersection(arr1, arr2, arr3) +# Output: [1,5] +# Explanation: Only 1 and 5 appeared in the three arrays. + +arr1 = [197,418,523,876,1356] +arr2 = [501,880,1593,1710,1870] +arr3 = [521,682,1337,1395,1764] +print arrays_intersection(arr1, arr2, arr3) +# Output: [] From 21e8bb04ef3d4346e1ba94dfb093fb7e1ed3cba3 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 10 Apr 2021 16:56:19 +0000 Subject: [PATCH 27/50] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index a34b83d..bd38b0d 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -14,6 +14,7 @@ ## Data Structures * Arrays * [Add Digits](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/add_digits.rb) + * [Arrays Intersection](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/arrays_intersection.rb) * [Find All Duplicates In An Array](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/find_all_duplicates_in_an_array.rb) * [Find The Highest Altitude](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/find_the_highest_altitude.rb) * [Fizz Buzz](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/fizz_buzz.rb) From fe4e56e8a4a04b3fc317477ad6a16e369f50bf1a Mon Sep 17 00:00:00 2001 From: Vitor Oliveira Date: Sat, 10 Apr 2021 09:57:25 -0700 Subject: [PATCH 28/50] Move to correct path --- data_structures/{arrays => hash_table}/arrays_intersection.rb | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename data_structures/{arrays => hash_table}/arrays_intersection.rb (100%) diff --git a/data_structures/arrays/arrays_intersection.rb b/data_structures/hash_table/arrays_intersection.rb similarity index 100% rename from data_structures/arrays/arrays_intersection.rb rename to data_structures/hash_table/arrays_intersection.rb From d6e7b9f1d8411d02a81664f517dbec81b56f9e27 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 10 Apr 2021 16:57:53 +0000 Subject: [PATCH 29/50] updating DIRECTORY.md --- DIRECTORY.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index bd38b0d..daeb2cc 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -14,7 +14,6 @@ ## Data Structures * Arrays * [Add Digits](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/add_digits.rb) - * [Arrays Intersection](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/arrays_intersection.rb) * [Find All Duplicates In An Array](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/find_all_duplicates_in_an_array.rb) * [Find The Highest Altitude](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/find_the_highest_altitude.rb) * [Fizz Buzz](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/fizz_buzz.rb) @@ -38,6 +37,7 @@ * [Preorder Traversal](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/binary_trees/preorder_traversal.rb) * Hash Table * [Anagram Checker](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/hash_table/anagram_checker.rb) + * [Arrays Intersection](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/hash_table/arrays_intersection.rb) * [Find All Duplicates In An Array](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/hash_table/find_all_duplicates_in_an_array.rb) * [Richest Customer Wealth](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/hash_table/richest_customer_wealth.rb) * [Two Sum](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/hash_table/two_sum.rb) From 745b66227bb05231d401d51e558a00aae42d3a39 Mon Sep 17 00:00:00 2001 From: Vitor Oliveira Date: Sat, 10 Apr 2021 10:04:40 -0700 Subject: [PATCH 30/50] Minor changes --- .../hash_table/arrays_intersection.rb | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/data_structures/hash_table/arrays_intersection.rb b/data_structures/hash_table/arrays_intersection.rb index cf1c1dc..7d270fc 100644 --- a/data_structures/hash_table/arrays_intersection.rb +++ b/data_structures/hash_table/arrays_intersection.rb @@ -32,24 +32,25 @@ def arrays_intersection(arr1, arr2, arr3) add_to_hash(arr2, hash) add_to_hash(arr3, hash) - hash.select { |key, value| value == 3 }.keys + hash.select { |_key, value| value == 3 }.keys end def add_to_hash(arr, hash) - arr.each_with_index do |value, index| - hash[value] += 1 + arr.count.times do |pointer| + value = arr[pointer] + hash[value] += 1 end end -arr1 = [1,2,3,4,5] -arr2 = [1,2,5,7,9] -arr3 = [1,3,4,5,8] +arr1 = [1, 2, 3, 4, 5] +arr2 = [1, 2, 5, 7, 9] +arr3 = [1, 3, 4, 5, 8] print arrays_intersection(arr1, arr2, arr3) # Output: [1,5] # Explanation: Only 1 and 5 appeared in the three arrays. -arr1 = [197,418,523,876,1356] -arr2 = [501,880,1593,1710,1870] -arr3 = [521,682,1337,1395,1764] +arr1 = [197, 418, 523, 876, 1356] +arr2 = [501, 880, 1593, 1710, 1870] +arr3 = [521, 682, 1337, 1395, 1764] print arrays_intersection(arr1, arr2, arr3) # Output: [] From 2197a587fb4d6405adc425adfa81bf06922c550b Mon Sep 17 00:00:00 2001 From: Vitor Oliveira Date: Sat, 10 Apr 2021 10:15:00 -0700 Subject: [PATCH 31/50] Update arrays_intersection.rb --- data_structures/hash_table/arrays_intersection.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/data_structures/hash_table/arrays_intersection.rb b/data_structures/hash_table/arrays_intersection.rb index 7d270fc..f100e37 100644 --- a/data_structures/hash_table/arrays_intersection.rb +++ b/data_structures/hash_table/arrays_intersection.rb @@ -32,7 +32,7 @@ def arrays_intersection(arr1, arr2, arr3) add_to_hash(arr2, hash) add_to_hash(arr3, hash) - hash.select { |_key, value| value == 3 }.keys + hash.select { |key, value| value == 3 }.keys end def add_to_hash(arr, hash) From ce0d1863a292cb69ab7ab01b4145e8e462058f29 Mon Sep 17 00:00:00 2001 From: Vitor Oliveira Date: Sat, 10 Apr 2021 10:38:43 -0700 Subject: [PATCH 32/50] Next greater element --- .../arrays/next_greater_element.rb | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 data_structures/arrays/next_greater_element.rb diff --git a/data_structures/arrays/next_greater_element.rb b/data_structures/arrays/next_greater_element.rb new file mode 100644 index 0000000..fc71766 --- /dev/null +++ b/data_structures/arrays/next_greater_element.rb @@ -0,0 +1,55 @@ +# You are given two integer arrays nums1 and nums2 both of unique elements, where nums1 is a subset of nums2. +# +# Find all the next greater numbers for nums1's elements in the corresponding places of nums2. +# +# The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, return -1 for this number. + +# Example 1: +# +# Input: nums1 = [4,1,2], nums2 = [1,3,4,2] +# Output: [-1,3,-1] +# +# Explanation: +# For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1. +# For number 1 in the first array, the next greater number for it in the second array is 3. +# For number 2 in the first array, there is no next greater number for it in the second array, so output -1. +# +# Example 2: +# +# Input: nums1 = [2,4], nums2 = [1,2,3,4] +# Output: [3,-1] +# +# Explanation: +# For number 2 in the first array, the next greater number for it in the second array is 3. +# For number 4 in the first array, there is no next greater number for it in the second array, so output -1. + +# @param {Integer[]} nums1 +# @param {Integer[]} nums2 +# @return {Integer[]} +def next_greater_element(nums1, nums2) + nums1.each_with_index do |value, pointer1| + max = 0 + pos_nums2 = nums2.find_index(value) + + nums2[pos_nums2..nums2.count].each do |value| + if value > nums1[pointer1] + max = value + break + end + end + + nums1[pointer1] = (nums1[pointer1] < max ? max : -1) + end + + nums1 +end + +nums1 = [4, 1, 2] +nums2 = [1, 3, 4, 2] +print next_greater_element(nums1, nums2) +# Output: [-1,3,-1] + +nums1 = [2, 4] +nums2 = [1, 2, 3, 4] +print next_greater_element(nums1, nums2) +# Output: [3,-1] From 1c9a26f389a5d62b60a10a7879c0eed848ec8c0f Mon Sep 17 00:00:00 2001 From: Vitor Oliveira Date: Sat, 10 Apr 2021 10:41:01 -0700 Subject: [PATCH 33/50] Minor changes --- data_structures/arrays/next_greater_element.rb | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/data_structures/arrays/next_greater_element.rb b/data_structures/arrays/next_greater_element.rb index fc71766..0790ab1 100644 --- a/data_structures/arrays/next_greater_element.rb +++ b/data_structures/arrays/next_greater_element.rb @@ -18,7 +18,7 @@ # # Input: nums1 = [2,4], nums2 = [1,2,3,4] # Output: [3,-1] -# +# # Explanation: # For number 2 in the first array, the next greater number for it in the second array is 3. # For number 4 in the first array, there is no next greater number for it in the second array, so output -1. @@ -27,18 +27,18 @@ # @param {Integer[]} nums2 # @return {Integer[]} def next_greater_element(nums1, nums2) - nums1.each_with_index do |value, pointer1| + nums1.each_with_index do |nums1_value, pointer1| max = 0 - pos_nums2 = nums2.find_index(value) + pos_nums2 = nums2.find_index(nums1_value) - nums2[pos_nums2..nums2.count].each do |value| - if value > nums1[pointer1] - max = value + nums2[pos_nums2..nums2.count].each do |nums2_value| + if nums2_value > nums1_value + max = nums2_value break end end - nums1[pointer1] = (nums1[pointer1] < max ? max : -1) + nums1[pointer1] = (nums1_value < max ? max : -1) end nums1 From 4e0d914d63c1eb4c4ea2eb436325b3e2992623cf Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 10 Apr 2021 17:41:17 +0000 Subject: [PATCH 34/50] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index c94db91..763e907 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -18,6 +18,7 @@ * [Find The Highest Altitude](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/find_the_highest_altitude.rb) * [Fizz Buzz](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/fizz_buzz.rb) * [Get Products Of All Other Elements](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/get_products_of_all_other_elements.rb) + * [Next Greater Element](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/next_greater_element.rb) * [Remove Elements](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/remove_elements.rb) * [Richest Customer Wealth](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/richest_customer_wealth.rb) * [Shuffle Array](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/shuffle_array.rb) From 4d9d7ca1cdad47591163d384c8de5f891f23c2a8 Mon Sep 17 00:00:00 2001 From: Vitor Oliveira Date: Sat, 10 Apr 2021 10:46:55 -0700 Subject: [PATCH 35/50] add complexity analysis --- data_structures/arrays/next_greater_element.rb | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/data_structures/arrays/next_greater_element.rb b/data_structures/arrays/next_greater_element.rb index 0790ab1..ffe957e 100644 --- a/data_structures/arrays/next_greater_element.rb +++ b/data_structures/arrays/next_greater_element.rb @@ -23,6 +23,15 @@ # For number 2 in the first array, the next greater number for it in the second array is 3. # For number 4 in the first array, there is no next greater number for it in the second array, so output -1. +# +# Approach: Brute Force +# + +# Complexity Analysis +# +# Time complexity : O(m*n). The complete nums1 array (of size n) needs to be scanned for all the m elements of nums2 in the worst case. +# Space complexity : O(1). No additional space since we're swapping elements in nums1 and returning the input array. + # @param {Integer[]} nums1 # @param {Integer[]} nums2 # @return {Integer[]} From 20d5ea3b6d419bd3b9fc62f07c3863607ff1c167 Mon Sep 17 00:00:00 2001 From: Vitor Oliveira Date: Sat, 10 Apr 2021 10:49:41 -0700 Subject: [PATCH 36/50] Update next_greater_element.rb --- data_structures/arrays/next_greater_element.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/data_structures/arrays/next_greater_element.rb b/data_structures/arrays/next_greater_element.rb index ffe957e..92b3344 100644 --- a/data_structures/arrays/next_greater_element.rb +++ b/data_structures/arrays/next_greater_element.rb @@ -29,8 +29,8 @@ # Complexity Analysis # -# Time complexity : O(m*n). The complete nums1 array (of size n) needs to be scanned for all the m elements of nums2 in the worst case. -# Space complexity : O(1). No additional space since we're swapping elements in nums1 and returning the input array. +# Time complexity: O(m*n). The complete nums1 array (of size n) needs to be scanned for all the m elements of nums2 in the worst case. +# Space complexity: O(1). No additional space since we're swapping elements in nums1 and returning the input array. # @param {Integer[]} nums1 # @param {Integer[]} nums2 From 1a8dc1debfad7e10719736dafd32edfbc291a393 Mon Sep 17 00:00:00 2001 From: Sahil Afrid Farookhi Date: Sun, 11 Apr 2021 00:36:28 +0530 Subject: [PATCH 37/50] add feature implementation --- maths/add.rb | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 maths/add.rb diff --git a/maths/add.rb b/maths/add.rb new file mode 100644 index 0000000..7351c32 --- /dev/null +++ b/maths/add.rb @@ -0,0 +1,20 @@ +# A ruby program to add numbers +# Addition or sum of numbers means adding each and every element of the inputs +# Sum or addition of 1 and 3 is 1 + 3 = 4 + +def self_add(*array) + sum = 0 + array.each { |a| sum+=a } + puts "The sum of following elements #{array} is #{sum}" + rescue + puts "Error: Please provide number only!" +end + +# Valid inputs +self_add(1) +self_add(2, 5, -4) +self_add(25, 45) + +# Invalid inputs +self_add("1", 2, 3) +self_add("a", 1) From f94eafd15a76817545647c5c408af416fd21ee15 Mon Sep 17 00:00:00 2001 From: maxbarsukov Date: Sun, 11 Apr 2021 14:39:22 +0300 Subject: [PATCH 38/50] The Searches folder is renamed to lowercase just like the other folders --- {Searches => searches}/binary_search.rb | 0 {Searches => searches}/depth_first_search.rb | 0 {Searches => searches}/double_linear_search.rb | 0 {Searches => searches}/jump_search.rb | 0 {Searches => searches}/linear_search.rb | 0 {Searches => searches}/recursive_double_linear_search.rb | 0 {Searches => searches}/recursive_linear_search.rb | 0 {Searches => searches}/ternary_search.rb | 0 8 files changed, 0 insertions(+), 0 deletions(-) rename {Searches => searches}/binary_search.rb (100%) rename {Searches => searches}/depth_first_search.rb (100%) rename {Searches => searches}/double_linear_search.rb (100%) rename {Searches => searches}/jump_search.rb (100%) rename {Searches => searches}/linear_search.rb (100%) rename {Searches => searches}/recursive_double_linear_search.rb (100%) rename {Searches => searches}/recursive_linear_search.rb (100%) rename {Searches => searches}/ternary_search.rb (100%) diff --git a/Searches/binary_search.rb b/searches/binary_search.rb similarity index 100% rename from Searches/binary_search.rb rename to searches/binary_search.rb diff --git a/Searches/depth_first_search.rb b/searches/depth_first_search.rb similarity index 100% rename from Searches/depth_first_search.rb rename to searches/depth_first_search.rb diff --git a/Searches/double_linear_search.rb b/searches/double_linear_search.rb similarity index 100% rename from Searches/double_linear_search.rb rename to searches/double_linear_search.rb diff --git a/Searches/jump_search.rb b/searches/jump_search.rb similarity index 100% rename from Searches/jump_search.rb rename to searches/jump_search.rb diff --git a/Searches/linear_search.rb b/searches/linear_search.rb similarity index 100% rename from Searches/linear_search.rb rename to searches/linear_search.rb diff --git a/Searches/recursive_double_linear_search.rb b/searches/recursive_double_linear_search.rb similarity index 100% rename from Searches/recursive_double_linear_search.rb rename to searches/recursive_double_linear_search.rb diff --git a/Searches/recursive_linear_search.rb b/searches/recursive_linear_search.rb similarity index 100% rename from Searches/recursive_linear_search.rb rename to searches/recursive_linear_search.rb diff --git a/Searches/ternary_search.rb b/searches/ternary_search.rb similarity index 100% rename from Searches/ternary_search.rb rename to searches/ternary_search.rb From b2fc530555f38f2da5f3fe173e5ae6f97b406ee3 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sun, 11 Apr 2021 22:56:29 +0000 Subject: [PATCH 39/50] updating DIRECTORY.md --- DIRECTORY.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index a34b83d..45e03fa 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -104,14 +104,14 @@ * [Sol1](https://github.com/TheAlgorithms/Ruby/blob/master/project_euler/problem_5/sol1.rb) ## Searches - * [Binary Search](https://github.com/TheAlgorithms/Ruby/blob/master/Searches/binary_search.rb) - * [Depth First Search](https://github.com/TheAlgorithms/Ruby/blob/master/Searches/depth_first_search.rb) - * [Double Linear Search](https://github.com/TheAlgorithms/Ruby/blob/master/Searches/double_linear_search.rb) - * [Jump Search](https://github.com/TheAlgorithms/Ruby/blob/master/Searches/jump_search.rb) - * [Linear Search](https://github.com/TheAlgorithms/Ruby/blob/master/Searches/linear_search.rb) - * [Recursive Double Linear Search](https://github.com/TheAlgorithms/Ruby/blob/master/Searches/recursive_double_linear_search.rb) - * [Recursive Linear Search](https://github.com/TheAlgorithms/Ruby/blob/master/Searches/recursive_linear_search.rb) - * [Ternary Search](https://github.com/TheAlgorithms/Ruby/blob/master/Searches/ternary_search.rb) + * [Binary Search](https://github.com/TheAlgorithms/Ruby/blob/master/searches/binary_search.rb) + * [Depth First Search](https://github.com/TheAlgorithms/Ruby/blob/master/searches/depth_first_search.rb) + * [Double Linear Search](https://github.com/TheAlgorithms/Ruby/blob/master/searches/double_linear_search.rb) + * [Jump Search](https://github.com/TheAlgorithms/Ruby/blob/master/searches/jump_search.rb) + * [Linear Search](https://github.com/TheAlgorithms/Ruby/blob/master/searches/linear_search.rb) + * [Recursive Double Linear Search](https://github.com/TheAlgorithms/Ruby/blob/master/searches/recursive_double_linear_search.rb) + * [Recursive Linear Search](https://github.com/TheAlgorithms/Ruby/blob/master/searches/recursive_linear_search.rb) + * [Ternary Search](https://github.com/TheAlgorithms/Ruby/blob/master/searches/ternary_search.rb) ## Sorting * [Bogo Sort](https://github.com/TheAlgorithms/Ruby/blob/master/sorting/bogo_sort.rb) From ae40765c38c30ef075f3c8c150f1dd28df282a21 Mon Sep 17 00:00:00 2001 From: Sahil Afrid Farookhi Date: Tue, 13 Apr 2021 00:58:45 +0530 Subject: [PATCH 40/50] average median feature implementation --- maths/average_median.rb | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 maths/average_median.rb diff --git a/maths/average_median.rb b/maths/average_median.rb new file mode 100644 index 0000000..52f86c2 --- /dev/null +++ b/maths/average_median.rb @@ -0,0 +1,37 @@ +# A ruby program to find average median + +module AverageMedian + + def self.average_median(n, *array) + if n.instance_of? Integer + if n == array.size + array.sort + if array.size%2 == 0 + mid_element_1 = array.size/2 + mid_element_2 = mid_element_1 + 1 + puts "The average median of the following elements #{array} is #{(array[mid_element_1-1] + array[mid_element_2-1])/2}." + else + mid_element = (array.size + 1)/2 + puts "The average median of the following elements #{array} is #{array[mid_element-1]}." + end + else + puts "Provide the required #{n} elements properly!" + end + else + raise + end + rescue + puts "Error: Please provide number only!" + end +end + +# Valid inputs +AverageMedian.average_median(2, 3, 1) +AverageMedian.average_median(5, 1, 2, 3, 4, 5) +AverageMedian.average_median(3, 2, 2, 2) +AverageMedian.average_median(1, 5) + +# Invalid inputs +AverageMedian.average_median(2, 3, 1, 5) +AverageMedian.average_median(2, 3, "a") +AverageMedian.average_median("a", 1, 2) From 0df659abae276bb7b42821a4f30d0883fd6ef16e Mon Sep 17 00:00:00 2001 From: Vitor Oliveira Date: Wed, 14 Apr 2021 16:29:37 -0700 Subject: [PATCH 41/50] renaming --- maths/add.rb | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/maths/add.rb b/maths/add.rb index 7351c32..1c756b4 100644 --- a/maths/add.rb +++ b/maths/add.rb @@ -2,7 +2,7 @@ # Addition or sum of numbers means adding each and every element of the inputs # Sum or addition of 1 and 3 is 1 + 3 = 4 -def self_add(*array) +def add(*array) sum = 0 array.each { |a| sum+=a } puts "The sum of following elements #{array} is #{sum}" @@ -11,10 +11,10 @@ def self_add(*array) end # Valid inputs -self_add(1) -self_add(2, 5, -4) -self_add(25, 45) +add(1) +add(2, 5, -4) +add(25, 45) # Invalid inputs -self_add("1", 2, 3) -self_add("a", 1) +add("1", 2, 3) +add("a", 1) From 82d71a94c7f82b27bce665c40eb43942d3257bd9 Mon Sep 17 00:00:00 2001 From: Vitor Oliveira Date: Wed, 14 Apr 2021 16:36:21 -0700 Subject: [PATCH 42/50] Update average_median.rb --- maths/average_median.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/maths/average_median.rb b/maths/average_median.rb index 52f86c2..5e94bd7 100644 --- a/maths/average_median.rb +++ b/maths/average_median.rb @@ -1,4 +1,5 @@ # A ruby program to find average median +# Reference: https://dev.to/colerau/how-to-find-the-median-and-mean-of-an-array-in-ruby-4f04 module AverageMedian From fbe6e9851d43c9c094aed24a5fe30c199aa465d3 Mon Sep 17 00:00:00 2001 From: Vitor Oliveira Date: Wed, 14 Apr 2021 16:39:13 -0700 Subject: [PATCH 43/50] add output --- maths/average_median.rb | 46 ++++++++++++++++++++++++++++++----------- 1 file changed, 34 insertions(+), 12 deletions(-) diff --git a/maths/average_median.rb b/maths/average_median.rb index 5e94bd7..9e447bd 100644 --- a/maths/average_median.rb +++ b/maths/average_median.rb @@ -2,18 +2,17 @@ # Reference: https://dev.to/colerau/how-to-find-the-median-and-mean-of-an-array-in-ruby-4f04 module AverageMedian - def self.average_median(n, *array) if n.instance_of? Integer if n == array.size array.sort - if array.size%2 == 0 + if array.size % 2 == 0 mid_element_1 = array.size/2 mid_element_2 = mid_element_1 + 1 - puts "The average median of the following elements #{array} is #{(array[mid_element_1-1] + array[mid_element_2-1])/2}." + puts "The average median of the following elements #{array} is #{(array[mid_element_1 - 1] + array[mid_element_2 - 1]) / 2}." else - mid_element = (array.size + 1)/2 - puts "The average median of the following elements #{array} is #{array[mid_element-1]}." + mid_element = (array.size + 1) / 2 + puts "The average median of the following elements #{array} is #{array[mid_element - 1]}." end else puts "Provide the required #{n} elements properly!" @@ -26,13 +25,36 @@ module AverageMedian end end +# # Valid inputs -AverageMedian.average_median(2, 3, 1) -AverageMedian.average_median(5, 1, 2, 3, 4, 5) -AverageMedian.average_median(3, 2, 2, 2) -AverageMedian.average_median(1, 5) +# +puts AverageMedian.average_median(2, 3, 1) +# The average median of the following elements [3, 1] is 2. + +puts AverageMedian.average_median(5, 1, 2, 3, 4, 5) +# The average median of the following elements [1, 2, 3, 4, 5] is 3. + +puts AverageMedian.average_median(3, 2, 2, 2) +# The average median of the following elements [2, 2, 2] is 2. + +puts AverageMedian.average_median(1, 5) +# The average median of the following elements [5] is 5. + +# # Invalid inputs -AverageMedian.average_median(2, 3, 1, 5) -AverageMedian.average_median(2, 3, "a") -AverageMedian.average_median("a", 1, 2) +# + +puts AverageMedian.average_median(2, 3, 1, 5) +# Provide the required 2 elements properly! + +puts AverageMedian.average_median(2, 3, "a") +# Traceback (most recent call last): +# 4: from /Users/voliveira/.rvm/rubies/ruby-2.7.0/bin/irb:23:in `
' +# 3: from /Users/voliveira/.rvm/rubies/ruby-2.7.0/bin/irb:23:in `load' +# 2: from /Users/voliveira/.rvm/rubies/ruby-2.7.0/lib/ruby/gems/2.7.0/gems/irb-1.2.1/exe/irb:11:in `' +# 1: from (irb):30 +# NameError (undefined local variable or method `verageMedian' for main:Object) + +puts AverageMedian.average_median("a", 1, 2) +# Error: Please provide number only! From 256f376574bc179d4e131a2ead1e546443efe223 Mon Sep 17 00:00:00 2001 From: Vitor Oliveira Date: Wed, 14 Apr 2021 16:40:39 -0700 Subject: [PATCH 44/50] add output for add algo --- maths/add.rb | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/maths/add.rb b/maths/add.rb index 1c756b4..a8a6c35 100644 --- a/maths/add.rb +++ b/maths/add.rb @@ -10,11 +10,25 @@ def add(*array) puts "Error: Please provide number only!" end +# # Valid inputs -add(1) -add(2, 5, -4) -add(25, 45) +# +puts add(1) +# The sum of following elements [1] is 1 + +puts add(2, 5, -4) +# The sum of following elements [2, 5, -4] is 3 + +puts add(25, 45) +# The sum of following elements [25, 45] is 70 + +# # Invalid inputs -add("1", 2, 3) -add("a", 1) +# + +puts add("1", 2, 3) +# Error: Please provide number only! + +puts add("a", 1) +# Error: Please provide number only! From 0f3441c0882faa759dcfcccb021631e0f5b45dd0 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Wed, 14 Apr 2021 23:41:50 +0000 Subject: [PATCH 45/50] updating DIRECTORY.md --- DIRECTORY.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 4f8a0a7..df4f340 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -65,10 +65,12 @@ ## Maths * [Abs](https://github.com/TheAlgorithms/Ruby/blob/master/maths/abs.rb) * [Abs Test](https://github.com/TheAlgorithms/Ruby/blob/master/maths/abs_test.rb) + * [Add](https://github.com/TheAlgorithms/Ruby/blob/master/maths/add.rb) * [Add Digits](https://github.com/TheAlgorithms/Ruby/blob/master/maths/add_digits.rb) * [Aliquot Sum](https://github.com/TheAlgorithms/Ruby/blob/master/maths/aliquot_sum.rb) * [Aliquot Sum Test](https://github.com/TheAlgorithms/Ruby/blob/master/maths/aliquot_sum_test.rb) * [Average Mean](https://github.com/TheAlgorithms/Ruby/blob/master/maths/average_mean.rb) + * [Average Median](https://github.com/TheAlgorithms/Ruby/blob/master/maths/average_median.rb) * [Binary To Decimal](https://github.com/TheAlgorithms/Ruby/blob/master/maths/binary_to_decimal.rb) * [Ceil](https://github.com/TheAlgorithms/Ruby/blob/master/maths/ceil.rb) * [Ceil Test](https://github.com/TheAlgorithms/Ruby/blob/master/maths/ceil_test.rb) From 50e6dc6f86993d9ad93fdf4760d4204fcc49fd9c Mon Sep 17 00:00:00 2001 From: Vitor Oliveira Date: Thu, 15 Apr 2021 17:25:30 -0700 Subject: [PATCH 46/50] Arrays intersection: two-pointer approach --- data_structures/arrays/arrays_intersection.rb | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 data_structures/arrays/arrays_intersection.rb diff --git a/data_structures/arrays/arrays_intersection.rb b/data_structures/arrays/arrays_intersection.rb new file mode 100644 index 0000000..63db80e --- /dev/null +++ b/data_structures/arrays/arrays_intersection.rb @@ -0,0 +1,67 @@ +# Given three integer arrays arr1, arr2 and arr3 sorted in strictly increasing order, return a sorted array of only the integers that appeared in all three arrays. +# +# Example 1: +# +# Input: arr1 = [1,2,3,4,5], arr2 = [1,2,5,7,9], arr3 = [1,3,4,5,8] +# Output: [1,5] +# Explanation: Only 1 and 5 appeared in the three arrays. +# +# Example 2: +# +# Input: arr1 = [197,418,523,876,1356], arr2 = [501,880,1593,1710,1870], arr3 = [521,682,1337,1395,1764] +# Output: [] +# +# + +# +# Approach: Two-pointer +# + +# Complexity Analysis +# +# Time Complexity: O(n), where n is the total length of all of the +# input arrays. +# Space Complexity: O(1), as we only initiate three integer variables +# using constant space. + +# @param {Integer[]} arr1 +# @param {Integer[]} arr2 +# @param {Integer[]} arr3 +# @return {Integer[]} +def arrays_intersection(arr1, arr2, arr3) + result = [] + + # prepare three pointers to iterate through three arrays + # p1, p2, and p3 point to the beginning of arr1, arr2, and arr3 accordingly + p1 = p2 = p3 = 0 + + while (p1 < arr1.count) && (p2 < arr2.count) && (p3 < arr3.count) + if arr1[p1] == arr2[p2] && arr1[p1] == arr3[p3] + result.push(arr1[p1]) + + p1 += 1 + p2 += 1 + p3 += 1 + elsif arr1[p1] < arr2[p2] + p1 += 1 + elsif arr2[p2] < arr3[p3] + p2 += 1 + else + p3 += 1 + end + end + + result +end + +arr1 = [1, 2, 3, 4, 5] +arr2 = [1, 2, 5, 7, 9] +arr3 = [1, 3, 4, 5, 8] +print(arrays_intersection(arr1, arr2, arr3)) +# Output: [1,5] + +arr1 = [197, 418, 523, 876, 1356] +arr2 = [501, 880, 1593, 1710, 1870] +arr3 = [521, 682, 1337, 1395, 1764] +print(arrays_intersection(arr1, arr2, arr3)) +# Output: [] From 6a076bde0750af89a078e98a49c0e7c0b4735f33 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Fri, 16 Apr 2021 00:25:50 +0000 Subject: [PATCH 47/50] updating DIRECTORY.md --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index df4f340..4c08933 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -14,6 +14,7 @@ ## Data Structures * Arrays * [Add Digits](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/add_digits.rb) + * [Arrays Intersection](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/arrays_intersection.rb) * [Find All Duplicates In An Array](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/find_all_duplicates_in_an_array.rb) * [Find The Highest Altitude](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/find_the_highest_altitude.rb) * [Fizz Buzz](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/fizz_buzz.rb) From da89bae9314f1dc838ec299556324908a479f1f3 Mon Sep 17 00:00:00 2001 From: Vitor Oliveira Date: Thu, 15 Apr 2021 17:27:27 -0700 Subject: [PATCH 48/50] Update arrays_intersection.rb --- data_structures/arrays/arrays_intersection.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/data_structures/arrays/arrays_intersection.rb b/data_structures/arrays/arrays_intersection.rb index 63db80e..c9780e0 100644 --- a/data_structures/arrays/arrays_intersection.rb +++ b/data_structures/arrays/arrays_intersection.rb @@ -14,7 +14,7 @@ # # -# Approach: Two-pointer +# Approach: Two-pointers # # Complexity Analysis From b101ef25d7aec58f631293f0ff91c355c298120a Mon Sep 17 00:00:00 2001 From: Vitor Oliveira Date: Thu, 15 Apr 2021 18:00:29 -0700 Subject: [PATCH 49/50] Update and rename arrays_intersection.rb to sorted_arrays_intersection.rb --- ...arrays_intersection.rb => sorted_arrays_intersection.rb} | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) rename data_structures/arrays/{arrays_intersection.rb => sorted_arrays_intersection.rb} (90%) diff --git a/data_structures/arrays/arrays_intersection.rb b/data_structures/arrays/sorted_arrays_intersection.rb similarity index 90% rename from data_structures/arrays/arrays_intersection.rb rename to data_structures/arrays/sorted_arrays_intersection.rb index c9780e0..a48a7c2 100644 --- a/data_structures/arrays/arrays_intersection.rb +++ b/data_structures/arrays/sorted_arrays_intersection.rb @@ -28,7 +28,7 @@ # @param {Integer[]} arr2 # @param {Integer[]} arr3 # @return {Integer[]} -def arrays_intersection(arr1, arr2, arr3) +def sorted_arrays_intersection(arr1, arr2, arr3) result = [] # prepare three pointers to iterate through three arrays @@ -57,11 +57,11 @@ end arr1 = [1, 2, 3, 4, 5] arr2 = [1, 2, 5, 7, 9] arr3 = [1, 3, 4, 5, 8] -print(arrays_intersection(arr1, arr2, arr3)) +print(sorted_arrays_intersection(arr1, arr2, arr3)) # Output: [1,5] arr1 = [197, 418, 523, 876, 1356] arr2 = [501, 880, 1593, 1710, 1870] arr3 = [521, 682, 1337, 1395, 1764] -print(arrays_intersection(arr1, arr2, arr3)) +print(sorted_arrays_intersection(arr1, arr2, arr3)) # Output: [] From b1131f996a577f874dd3470d373daed7cf302c83 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Fri, 16 Apr 2021 01:00:45 +0000 Subject: [PATCH 50/50] updating DIRECTORY.md --- DIRECTORY.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index 4c08933..1028fcd 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -14,7 +14,6 @@ ## Data Structures * Arrays * [Add Digits](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/add_digits.rb) - * [Arrays Intersection](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/arrays_intersection.rb) * [Find All Duplicates In An Array](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/find_all_duplicates_in_an_array.rb) * [Find The Highest Altitude](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/find_the_highest_altitude.rb) * [Fizz Buzz](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/fizz_buzz.rb) @@ -25,6 +24,7 @@ * [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) + * [Sorted Arrays Intersection](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/sorted_arrays_intersection.rb) * Strings * [Anagram Checker](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/strings/anagram_checker.rb) * [Jewels And Stones](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/strings/jewels_and_stones.rb)