The document discusses three algorithms:
1. A function to check if a string has balanced parentheses. It counts the number of opening and closing parentheses and returns True if they are equal.
2. A function to find the first converging node of two linked lists. It iterates through both lists simultaneously and returns the first common node.
3. A function to print all pairs of integers in an array that sum to a given value X. It uses a dictionary to store the elements and iterates through the array, checking if the complement to reach X exists in the dictionary.
Download as TXT, PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
110 views
Amazon Interview
The document discusses three algorithms:
1. A function to check if a string has balanced parentheses. It counts the number of opening and closing parentheses and returns True if they are equal.
2. A function to find the first converging node of two linked lists. It iterates through both lists simultaneously and returns the first common node.
3. A function to print all pairs of integers in an array that sum to a given value X. It uses a dictionary to store the elements and iterates through the array, checking if the complement to reach X exists in the dictionary.
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3
Check if string has balanced parenthesis.
Eg: ()() , ((()
def checkbalanced (s): open_par,closed_par=0,0; for char in s: if char=='(': open_par+=1 elif char==')' and open_par>0: closed_par+=1
(HA)A -> B -> C -> D G -> (HB)E -> F -> C -> D Y A -> B -> D -> C A -> C Node converinglists(LN a, LN b){ if (heada==nullptr || headb==nullptr){ return NULL; } currenta=heada; currentb=headb; while (currenta != nullptr && currentb !=nullptr){ if (currenta==currentb){ return currenta; } else{ currenta=currenta->next; currentb=ccurentb->next; } return NULL;
def lists(ln a, lnb): dic1=dict() convergingNode=NULL; for e in a: //iterating through nodes in a if e in dict1: return e else: dic1[e]=1 for e in b: // iterating through nodes in b if e in dict1: return e else: dic1[e]=1
4 5
def lists (ln a, ln b): alen=len(a) blen=len(b) diff=0 if alen>blen: diff=alen-blen elif alen<blen: diff=-alen+blen for e in a[diff:-1]
a=4 a=-5 b=5 b=4
{0:A,1:B,2:C
Given an array of integers, write a method which prints all the pair of integers which sum upto X. [2 5 -3 9 12 7 10 2] X=9 def sumintergers(X, lst): dictlist=dict() aset=set() for e in range(len(lst)): dictlst[e]=lst[e] for e in lst: if dictlst[X-e]: set.add(X) if set not in X print(X-e,e)
{0:2,1:5,2:-3,3:9
for e in lst: for i in dictlist.values(): if X-e==i: print (e,i)