arr.push(4)# add to endarr.pop# remove from endarr.unshift(0)# add to startarr.shift# remove from startarr.include?(2)# check if existsarr.index(3)# get index of first occurrencearr.uniq# remove duplicatesarr.sort# sort arrayarr.reverse# reverse arrayarr.sum# sum of elements
Iteration
arr.each{|x|putsx}arr.map{|x|x*2}# returns new arrayarr.select{|x|x>2}# filterarr.reject{|x|x>2}# opposite of selectarr.reduce(0){|sum,x|sum+x}# fold/reduce
Time Complexity
Operation
Average
Worst
Access
O(1)
O(1)
Append/Push
O(1)
O(n)
Prepend/Unshift
O(n)
O(n)
Delete by index
O(n)
O(n)
Search
O(n)
O(n)
2. Hashes / Dictionaries
Creation
h={}# empty hashh={a: 1,b: 2}# initializedh=Hash.new(0)# default value
Common Operations
h[:c]=3# add/updateh.delete(:a)# delete keyh.key?(:b)# check existenceh.values# array of valuesh.keys# array of keysh.each{|k,v|puts"#{k}: #{v}"}
# Maximum Sum Subarray (Size k)defmax_subarray_sum(arr,k)returnnilifarr.size<kmax_sum=arr[0...k].sumcurrent_sum=max_sum(k...arr.size).eachdo|i|current_sum+=arr[i]-arr[i-k]max_sum=[max_sum,current_sum].maxendmax_sumend# Minimum Length Subarray (Sum β₯ target)defmin_subarray_len(arr,target)left=0sum=0min_len=Float::INFINITYarr.each_with_indexdo|num,right|sum+=numwhilesum>=targetmin_len=[min_len,right-left+1].minsum-=arr[left]left+=1endendmin_len==Float::INFINITY?0:min_lenend# Length of Longest Substring Without Repeating Charactersdeflength_of_longest_substring(s)seen={}left=0max_len=0s.chars.each_with_indexdo|c,right|ifseen.key?(c)&&seen[c]>=leftleft=seen[c]+1endseen[c]=rightmax_len=[max_len,right-left+1].maxendmax_lenend
Two Pointers
# Two Sum on Sorted Arraydeftwo_sum_sorted(arr,target)left,right=0,arr.length-1whileleft<rightsum=arr[left]+arr[right]return[left,right]ifsum==targetsum<target?left+=1:right-=1endnilend# Palindrome Checkdefpalindrome?(s)left,right=0,s.length-1whileleft<rightreturnfalseifs[left]!=s[right]left+=1right-=1endtrueend
10. Complexity Cheats
Structure / Operation
Avg Time
Worst Time
Space
Array Access
O(1)
O(1)
O(n)
Array Search
O(n)
O(n)
O(1)
Hash Lookup
O(1)
O(n)
O(n)
Stack/Queue
O(1)
O(1)
O(n)
BST Lookup
O(log n)
O(n)
O(n)
Heap Insert/Extract
O(log n)
O(log n)
O(n)
Graph Traversal BFS/DFS
O(V+E)
O(V+E)
O(V)
Sorting
O(n log n)
O(n log n)
O(n)
This cheat sheet covers Ruby-specific methods, common data structures, algorithm patterns, and their complexities for thorough DSA prep.
Top comments (0)
Subscribe
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Top comments (0)