├── images └── quoteTorvalds.jpg ├── Geometry ├── readme.md └── CLOPPAIR.cpp ├── List Shuffling ├── ListShuffling.pdf ├── readme.md └── List Shuffling.cpp ├── Loop Detector.py ├── Dynamic Programming ├── images │ ├── editDistance.jpeg │ ├── k-palindrome.jpeg │ ├── Out of Boundary Paths.jpeg │ └── Max Profit with K Transactions.jpeg ├── pdf │ ├── coin change ways.pdf │ └── uniqueBSTwithCatlanNumbers.pdf ├── increasingTripletSubsequence.cpp ├── maxProfitWithAtmost1Transaction.cpp ├── uniqueBST.cpp ├── maxProfitWithkTransactions.cpp ├── Move_to_other_end.py ├── k-palindrome.cpp ├── longestPalindromicSubsequence.cpp ├── longestValidParenthesis.cpp ├── Out of Boundary Paths.cpp ├── LCS.cpp ├── editDistance.cpp ├── longestArithematicProgression.cpp ├── coinChange2.cpp ├── shortestCommonSupersequence.cpp └── readme.md ├── Is Palindrome.py ├── Count distinct elements in every window of size k.py ├── Count no of digits in Integer without Loops.py ├── Delete Middle Node.py ├── Sort Binary Array.py ├── Move Zeroes to End.py ├── Modify One Element.py ├── Smallest window that contains all distinct characters.py ├── Climbing Stairs.py ├── First negative integer in every window of size k.py ├── Pair Sum.py ├── N-th Prefect Number.cpp ├── linkedList ├── deleteNodeWithoutHeader.cpp ├── mergeKsortedLists.cpp ├── swapNodesInPairs.cpp ├── swapNodesInkGroup.cpp ├── readme.md └── lru.cpp ├── Longest Palindromic Substring.py ├── contiguous_array_sums.py ├── sorting ├── readme.md └── LargestNumber.cpp ├── Find the smallest window in a string containing all characters of another string.py ├── Peak_elements.py ├── curry.py ├── Design Problems ├── readme.md ├── hashset.c ├── hashmap.c ├── circularQueue.c ├── implement-trie-prefix-tree.cpp ├── circularDeque.c ├── browserHistory.cpp └── designTwitter.cpp ├── MissingNumbers.cpp ├── amdocs_pattern.py ├── sortRGB.cpp ├── Two Elements.py ├── bitManipulation ├── readme.md └── reverseBits.cpp ├── Happy Number.py ├── RangeSum.cpp ├── Reverse Words in String.cpp ├── twoPointers ├── containerWithMostWater.cpp ├── longestSubstringWithoutRepeatingCharacters.cpp └── readme.md ├── 2D Array ├── readme.md └── searchIn2DMatrix.cpp ├── place_all_x_and_y_together.cpp ├── hashMap ├── longestFibonacciSubsequence.cpp ├── longestConesutiveSequence.cpp └── readme.md ├── sets ├── readme.md └── mergingIntervals.cpp ├── getTargetSum.py ├── Sorted and Rotated Array.cpp ├── Is Palindrome.cpp ├── Fenwick Trees ├── tutorial │ ├── readme.md │ └── FENTREE.cpp ├── readme.md ├── Count_of_Smaller_Numbers_After_Self.cpp ├── createSortedArrayThroughInstructions.cpp └── range-sum-query-mutable.cpp ├── missingKnaturalNumbers.cpp ├── Tree Algorithms ├── maxDepthOfBinTree.cpp ├── minDepthOfBinTree.cpp ├── insertTreeIntoBST.cpp ├── maxLevelSumOfBinaryTree.cpp ├── binTreeRightSideView.cpp ├── binTreeZigZagLevelOrderTraversal.cpp └── readme.md ├── UnivalSubtrees.cpp ├── Find First and Last Position of Element in Sorted Array.py ├── odd_even_link_list_o(n).c ├── merge_two_sorted_list.c ├── Union Find ├── readme.md ├── redundantConnections.cpp ├── CouplesHoldingHands.cpp └── accounts-merge.cpp ├── runLengthEncoding.cpp ├── Odd Even Linked List.c ├── FindMedianFromDataStream.cpp ├── validParenthesis.py ├── Towers and Listeners.py ├── SentenceEquality.cpp ├── numberofIslands.cpp ├── Find_the_celebrity.cpp ├── spiral_matrix.py ├── Backtracking └── sudokuSolver.cpp └── README.md /images/quoteTorvalds.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/siddharthrajaraja/Interview-Problems/HEAD/images/quoteTorvalds.jpg -------------------------------------------------------------------------------- /Geometry/readme.md: -------------------------------------------------------------------------------- 1 | ## Closest Pair of Points 2 | 3 | _Link to problem_: [CLOPPAIR](https://www.spoj.com/problems/CLOPPAIR/) 4 | -------------------------------------------------------------------------------- /List Shuffling/ListShuffling.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/siddharthrajaraja/Interview-Problems/HEAD/List Shuffling/ListShuffling.pdf -------------------------------------------------------------------------------- /Loop Detector.py: -------------------------------------------------------------------------------- 1 | l=list(map(int,input().split())) 2 | l.pop() 3 | k=int(input()) 4 | 5 | if k in l: 6 | print(k) 7 | else: 8 | print("null") -------------------------------------------------------------------------------- /Dynamic Programming/images/editDistance.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/siddharthrajaraja/Interview-Problems/HEAD/Dynamic Programming/images/editDistance.jpeg -------------------------------------------------------------------------------- /Dynamic Programming/images/k-palindrome.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/siddharthrajaraja/Interview-Problems/HEAD/Dynamic Programming/images/k-palindrome.jpeg -------------------------------------------------------------------------------- /Dynamic Programming/pdf/coin change ways.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/siddharthrajaraja/Interview-Problems/HEAD/Dynamic Programming/pdf/coin change ways.pdf -------------------------------------------------------------------------------- /Is Palindrome.py: -------------------------------------------------------------------------------- 1 | l=list(map(int,input().split())) 2 | l.pop() 3 | k=l[::] 4 | k.reverse() 5 | 6 | if k==l: 7 | print("true") 8 | else: 9 | print("false") -------------------------------------------------------------------------------- /Dynamic Programming/images/Out of Boundary Paths.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/siddharthrajaraja/Interview-Problems/HEAD/Dynamic Programming/images/Out of Boundary Paths.jpeg -------------------------------------------------------------------------------- /Dynamic Programming/pdf/uniqueBSTwithCatlanNumbers.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/siddharthrajaraja/Interview-Problems/HEAD/Dynamic Programming/pdf/uniqueBSTwithCatlanNumbers.pdf -------------------------------------------------------------------------------- /Dynamic Programming/images/Max Profit with K Transactions.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/siddharthrajaraja/Interview-Problems/HEAD/Dynamic Programming/images/Max Profit with K Transactions.jpeg -------------------------------------------------------------------------------- /Count distinct elements in every window of size k.py: -------------------------------------------------------------------------------- 1 | n=int(input()) 2 | l=list(map(int,input().split())) 3 | k=int(input()) 4 | for i in range(0,len(l)-k+1): 5 | m=l[i:i+k] 6 | print(len(list(set(m)))) 7 | 8 | -------------------------------------------------------------------------------- /Count no of digits in Integer without Loops.py: -------------------------------------------------------------------------------- 1 | def count_digits(n): 2 | if n==0: 3 | return 0 4 | return 1+count_digits(n//10) 5 | 6 | n=int(input()) 7 | 8 | digits=count_digits(n) 9 | print(digits) 10 | -------------------------------------------------------------------------------- /Delete Middle Node.py: -------------------------------------------------------------------------------- 1 | l=list(map(int,input().split())) 2 | 3 | l.pop() 4 | 5 | if len(l)%2==0: 6 | l.pop(len(l)//2-1) 7 | else: 8 | l.pop(len(l)//2) 9 | #print(l) 10 | for i in range(0,len(l)): 11 | print(l[i],end=" ") -------------------------------------------------------------------------------- /Sort Binary Array.py: -------------------------------------------------------------------------------- 1 | n=int(input()) 2 | 3 | l=list(map(int,input().split())) 4 | 5 | ones=0 6 | zeroes=0 7 | 8 | for i in range(0,len(l)): 9 | if l[i]==0: 10 | zeroes+=1 11 | else: 12 | ones+=1 13 | 14 | ans=list('0'*zeroes+'1'*ones) 15 | print(" ".join(ans)) 16 | -------------------------------------------------------------------------------- /Move Zeroes to End.py: -------------------------------------------------------------------------------- 1 | # Write your code here 2 | n=int(input()) 3 | l=list(map(int,input().split())) 4 | zeros=0 5 | ans=[] 6 | for i in range(0,len(l)): 7 | if l[i]!=0: 8 | print(l[i],end=" ") 9 | else: 10 | zeros+=1 11 | for i in range(0,zeros): 12 | print(0,end=" ") 13 | -------------------------------------------------------------------------------- /Modify One Element.py: -------------------------------------------------------------------------------- 1 | n=int(input()) 2 | l=list(map(int,input().split())) 3 | c=0 4 | flag=0 5 | for i in range(1,len(l)): 6 | if l[i]1: 9 | print("flase") 10 | 11 | break 12 | 13 | if c<=1: 14 | print("true") 15 | 16 | -------------------------------------------------------------------------------- /Smallest window that contains all distinct characters.py: -------------------------------------------------------------------------------- 1 | s=list(input()) 2 | dis=set(s) 3 | 4 | ans=[] 5 | for i in range(0,len(s)-len(dis)+1): 6 | for j in range(1,len(s)): 7 | if set(s[i:j+1])==dis: 8 | ans.append([len(s[i:j+1]),s[i:j+1]]) 9 | ans.sort() 10 | print("".join(ans[0][1])) -------------------------------------------------------------------------------- /Climbing Stairs.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def climbStairs(self, n: int) -> int: 3 | if n==0: 4 | return 0 5 | if n==1: 6 | return 1 7 | 8 | arr=[0,1] 9 | 10 | while n!=0: 11 | arr.append(arr[-1]+arr[-2]) 12 | n=n-1 13 | return arr[-1] -------------------------------------------------------------------------------- /First negative integer in every window of size k.py: -------------------------------------------------------------------------------- 1 | n=int(input()) 2 | l=list(map(int,input().split())) 3 | 4 | k=int(input()) 5 | 6 | for i in range(0,len(l)-k+1): 7 | m=l[i:i+k] 8 | #print(m) 9 | flag=0 10 | for j in range(0,len(m)): 11 | if m[j]<0: 12 | print(m[j],end=" ") 13 | flag=1 14 | break 15 | if flag!=1: 16 | print(0,end=" ") -------------------------------------------------------------------------------- /Pair Sum.py: -------------------------------------------------------------------------------- 1 | n=int(input()) 2 | l=[] 3 | for i in range(0,n): 4 | l.append(int(input())) 5 | k=int(input()) 6 | 7 | ans=[] 8 | for i in range(0,len(l)): 9 | if k-l[i] in l: 10 | sol1=(l[i],k-l[i]) 11 | sol2=(k-l[i],l[i]) 12 | if sol1 not in ans or sol2 not in ans: 13 | ans.append(sol1) 14 | #print(ans) 15 | for i in range(0,len(ans)//2): 16 | print(ans[i][0],"and",ans[i][1]) 17 | 18 | 19 | -------------------------------------------------------------------------------- /N-th Prefect Number.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define MAX 100000 3 | long long int A[MAX]; 4 | 5 | int getSum(long n){ 6 | long s=0; 7 | while(n!=0){ 8 | s=s+(n%10); 9 | n=n/10; 10 | } 11 | if(s==10)return 1; 12 | return 0; 13 | } 14 | 15 | int main(){ 16 | int n; 17 | scanf("%d",&n); 18 | int i=0,j=0; 19 | for(i=0;;i++){ 20 | if(j>1000)break; 21 | if(getSum(i)==1)A[j++]=i; 22 | } 23 | printf("%lld",A[n-1]); 24 | 25 | return 0; 26 | } -------------------------------------------------------------------------------- /linkedList/deleteNodeWithoutHeader.cpp: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | struct Node { 4 | int data; 5 | struct Node *next; 6 | Node(int x) { 7 | data = x; 8 | next = NULL; 9 | } 10 | }*head; 11 | */ 12 | void deleteNode(Node *node) 13 | { 14 | Node *p=node,*q; 15 | while(p->next!=NULL ){ 16 | q=p; 17 | p->data=p->next->data; 18 | p=p->next; 19 | } 20 | 21 | q->next=NULL; 22 | 23 | // Your code here 24 | } 25 | -------------------------------------------------------------------------------- /Longest Palindromic Substring.py: -------------------------------------------------------------------------------- 1 | s=list(input()) 2 | 3 | for i in range(0,len(s)): 4 | for j in range(i+1,len(s)): 5 | #print(s[i:j]) 6 | m=s[i:j] 7 | print(m) 8 | if len(m)%2!=0: 9 | mr=m[i:j//2] 10 | ml=m[j//2:] 11 | ml.reverse() 12 | else: 13 | mr=m[i:j//2+1] 14 | ml=m[j//2:] 15 | ml.reverse() 16 | 17 | if mr==ml: 18 | print("".join(m)) 19 | 20 | -------------------------------------------------------------------------------- /contiguous_array_sums.py: -------------------------------------------------------------------------------- 1 | #Consider single element to be a subarray 2 | def checkSubarraySum(nums,k): 3 | s=nums[0] 4 | i=1 5 | j=0 6 | while iarr[m-1] and arr[m]>arr[m+1]: 9 | ans.append(True) 10 | solutions.append(arr[m]) 11 | 12 | check(arr,l,m-1) 13 | check(arr,m+1,u) 14 | l=list(map(int,input().split())) 15 | check(l,0,len(l)-1) 16 | 17 | if True in ans : 18 | print("YES") 19 | print("ALL PEAK ELEMENTS ARE :",solutions) 20 | else: 21 | print("NO") 22 | -------------------------------------------------------------------------------- /curry.py: -------------------------------------------------------------------------------- 1 | 2 | class addSubtract(int): 3 | list=[] 4 | def __call__(self, v): 5 | self.list.append(v) 6 | return type(self)(v) 7 | def printList(self): 8 | print("yaha hu",self.list) 9 | def getResult(self): 10 | if len(self.list)==0: 11 | return 0 12 | s=self.list[0] 13 | for i in range(1,len(self.list)): 14 | if i%2==0: 15 | s=s-self.list[i] 16 | else: 17 | s=s+self.list[i] 18 | return s 19 | print(addSubtract()(7).getResult()) -------------------------------------------------------------------------------- /Design Problems/readme.md: -------------------------------------------------------------------------------- 1 | # Design Problems 2 | 3 | ### [Circular Queues](https://leetcode.com/problems/design-circular-queue/) 4 | 5 | --- 6 | 7 | ### [Circular Deque](https://leetcode.com/problems/design-circular-deque/) 8 | 9 | --- 10 | 11 | ### [Hashmap](https://leetcode.com/problems/design-hashmap) 12 | 13 | --- 14 | 15 | ### [Hashset](https://leetcode.com/problems/design-hashset/) 16 | 17 | --- 18 | 19 | ### [Implement-Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) 20 | 21 | --- 22 | 23 | ### [Design Twitter](https://leetcode.com/problems/design-twitter/) 24 | -------------------------------------------------------------------------------- /MissingNumbers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | #define MAX 10000001 6 | int visited[MAX]={}; 7 | 8 | void input(long long n){ 9 | 10 | while(n!=0){ 11 | long long ele; std::cin>>ele; 12 | visited[ele]=1; 13 | n--; 14 | } 15 | 16 | } 17 | 18 | void solution(long long n){ 19 | long long i=1; 20 | while(i<=n){ 21 | if(visited[i]==0)std::cout<>n; 30 | 31 | input(n); 32 | solution(n); 33 | 34 | return 0; 35 | } -------------------------------------------------------------------------------- /amdocs_pattern.py: -------------------------------------------------------------------------------- 1 | 2 | n=int(input()) 3 | value=1 4 | array=[] 5 | for i in range(0,n): 6 | j=0 7 | l=[] 8 | while j<=i: 9 | l.append(value) 10 | j=j+1 11 | value+=1 12 | if i%2!=0: 13 | l.reverse() 14 | 15 | array.append(l) 16 | 17 | for i in range(0,len(array)): 18 | L=array[i] 19 | l=[] 20 | for j in range(0,len(L)): 21 | l.append(L[j]) 22 | if j!=len(L)-1: 23 | 24 | l.append("*") 25 | array[i]=l 26 | for i in range(0,len(array)): 27 | for j in range(0,len(array[i])): 28 | print(array[i][j],end=" ") 29 | print() 30 | 31 | -------------------------------------------------------------------------------- /sortRGB.cpp: -------------------------------------------------------------------------------- 1 | typedef long long ll; 2 | using namespace std; 3 | 4 | void solve(char input[]) { 5 | ll R=0; 6 | ll B=0; 7 | ll G=0; 8 | 9 | for(ll i=0;input[i];i++){ 10 | if(input[i]=='R')R++; 11 | if(input[i]=='G')G++; 12 | if(input[i]=='B')B++; 13 | 14 | } 15 | ll i=0; 16 | while(R!=0){ 17 | input[i]='R'; 18 | R--; 19 | i++; 20 | } 21 | 22 | while(G!=0){ 23 | input[i]='G'; 24 | G--; 25 | i++; 26 | } 27 | 28 | while(B!=0){ 29 | input[i]='B'; 30 | B--; 31 | i++; 32 | } 33 | 34 | } 35 | 36 | -------------------------------------------------------------------------------- /Two Elements.py: -------------------------------------------------------------------------------- 1 | n=int(input()) 2 | l=list(map(int,input().split())) 3 | 4 | positive=list(map(int,'0'*1000000)) 5 | negative=list(map(int,'0'*1000000)) 6 | zeroes=0 7 | for i in range(0,len(l)): 8 | if l[i]<0: 9 | negative[abs(l[i])]+=1 10 | elif l[i]>0: 11 | positive[l[i]]+=1 12 | elif l[i]==0: 13 | zeroes+=1 14 | ans=[] 15 | 16 | if zeroes==1: 17 | ans=[0] 18 | 19 | for i in range(0,len(negative)): 20 | if negative[i]==1: 21 | 22 | ans.append(-1*i) 23 | if positive[i]==1: 24 | ans.append(i) 25 | for i in range(0,len(ans)): 26 | print(ans[i]) 27 | #print(ans) 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /bitManipulation/readme.md: -------------------------------------------------------------------------------- 1 | # Bits '1s' or '0s' ? 2 | 3 | ### Reverse Bits 💯 : 4 | 5 | #### Link to problem : [Leetcode](https://leetcode.com/problems/reverse-bits/) or [Interview Bit](https://www.interviewbit.com/problems/reverse-bits/) 6 | 7 | #### Intution 👍: 8 | 9 | 1. Think of a container that helps you reverse a list of values . 10 | 2. What kind of values can this container have ? (HINT : 0s and 1s) 11 | 3. How are you going to get the set or unset values out of the input unsigned integer provided ? Can you get the bits optimally? (Hint: Bit manipulation). 12 | 4. Reverse the container and try to obtain the result by applying reverse Engineering . 😄 😸 -------------------------------------------------------------------------------- /Happy Number.py: -------------------------------------------------------------------------------- 1 | def getSquare(n): 2 | s=0 3 | while n!=0: 4 | s=s+pow(n%10,2) 5 | 6 | n=n//10 7 | return s 8 | 9 | visit=[] 10 | 11 | for i in range(0,10001): 12 | visit.append(0) 13 | 14 | visit[0]=1 15 | if __name__=="__main__": 16 | n=int(input()) 17 | 18 | while True: 19 | 20 | if (n in range(0,10001) and visit[n-1]==1 or set(visit)=={1}): 21 | break 22 | if n in range(0,10001): 23 | 24 | visit[n-1]=1 25 | n=getSquare(n) 26 | 27 | #print(n) 28 | if(n==1): 29 | 30 | print("true") 31 | else: 32 | print("false") 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /Dynamic Programming/increasingTripletSubsequence.cpp: -------------------------------------------------------------------------------- 1 | #define REP(i, a, b) for (int i = a; i < b; i++) 2 | class Solution 3 | { 4 | public: 5 | bool increasingTriplet(vector &nums) 6 | { 7 | 8 | int oneMin = INT_MAX; 9 | int twoMin = INT_MAX; 10 | 11 | int i; 12 | int size = nums.size(); 13 | 14 | REP(i, 0, size) 15 | { 16 | 17 | if (nums[i] < oneMin) 18 | { 19 | oneMin = nums[i]; 20 | } 21 | else if (nums[i] > oneMin) 22 | { 23 | if (twoMin < nums[i]) 24 | return true; 25 | twoMin = nums[i]; 26 | } 27 | } 28 | return false; 29 | } 30 | }; -------------------------------------------------------------------------------- /Dynamic Programming/maxProfitWithAtmost1Transaction.cpp: -------------------------------------------------------------------------------- 1 | typedef long long ll; 2 | class Solution { 3 | public: 4 | int maxProfit(vector& prices) { 5 | priority_queue,greater>arr; 6 | ll present=-1; 7 | ll profit=0; 8 | 9 | for(auto ele:prices){ 10 | present=ele; 11 | if(arr.empty()){ 12 | arr.push(ele);profit=0; 13 | } 14 | else{ 15 | //cout<<"Topmost ele: "<ans2)return true; 5 | return false; 6 | } 7 | class Solution { 8 | public: 9 | 10 | 11 | 12 | string largestNumber(vector& nums) { 13 | 14 | vectorarr; 15 | int intCount=0; 16 | for(auto ele:nums){ 17 | if(ele==0)intCount++; 18 | arr.push_back(to_string(ele)); 19 | } 20 | if(intCount==nums.size())return "0"; 21 | 22 | sort(arr.begin(),arr.end(),comp); 23 | string ans=""; 24 | for(auto ele:arr){ 25 | ans+=ele; 26 | } 27 | return ans; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /RangeSum.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | long long S=0; 11 | class Solution { 12 | public: 13 | 14 | void getTree( TreeNode *root,int L,int R){ 15 | if(root!=NULL){ 16 | getTree(root->left,L,R); 17 | if(root->val>=L && root->val<=R)S+=root->val; 18 | getTree(root->right,L,R); 19 | } 20 | } 21 | 22 | int rangeSumBST(TreeNode* root, int L, int R) { 23 | getTree(root,L,R); 24 | long long sS=S; 25 | S=0; 26 | return sS; 27 | 28 | 29 | } 30 | }; -------------------------------------------------------------------------------- /bitManipulation/reverseBits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | uint32_t reverseBits(uint32_t n) { 4 | vectorQ; 5 | int times=0; 6 | while(times!=32){ 7 | if((n&(1< 2 | #include 3 | #define MAX 1000000 4 | char s[MAX]; 5 | int main(){ 6 | scanf("%[^\n]s",s); 7 | //puts(s); 8 | int i=strlen(s)-1; 9 | int j; 10 | int end; 11 | int index=0; 12 | char ans[strlen(s)]; 13 | 14 | while(s[i]==' ' && i>=0)i--; 15 | 16 | 17 | while (i>=0){ 18 | j=i; 19 | int k; 20 | while (j>=0){ 21 | //printf("%c\n",s[j]); 22 | if(s[j]==' ')break; 23 | j--; 24 | } 25 | if (i!=strlen(s)-1)ans[index++]=' '; 26 | //printf("%d",j); 27 | for(k=j+1;k<=i;k++){ 28 | //printf("%c",s[k]); 29 | ans[index++]=s[k]; 30 | 31 | } 32 | //printf("\n%d\n",k); 33 | i=j-1; 34 | //printf("%d",i); 35 | } 36 | puts(ans); 37 | 38 | return 0; 39 | } 40 | 41 | -------------------------------------------------------------------------------- /twoPointers/containerWithMostWater.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxArea(vector& height) { 4 | int maxi=INT_MIN; 5 | int i=0; 6 | int j=height.size()-1; 7 | while(iheight[j]){ 13 | j--; 14 | } 15 | else if(height[j]>height[i]){ 16 | i++; 17 | } 18 | else{ 19 | 20 | if(height[j-1] target : (This is because allElements in same row lesser then currentElement) 23 | x++ 24 | else: (This is because allElements in same column greater then currentElement) 25 | y-- 26 | 27 | 3) return True 28 | ``` 29 | 30 | --- 31 | -------------------------------------------------------------------------------- /place_all_x_and_y_together.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #define MAX 10000000 9 | 10 | using namespace std; 11 | 12 | 13 | int main(){ 14 | string s;std::cin>>s; 15 | int cx; 16 | int i=0; 17 | while(i 2 | using namespace std; 3 | typedef long long ll; 4 | #define MAX 100000 5 | #define REP(i,a,b) for(ll i=a;i>t; 27 | 28 | while(t--){ 29 | ll n;cin>>n; 30 | while(n--){ 31 | ll ele;cin>>ele; 32 | if(fib[ele]==1)cout< Not an efficient logic but a basic approach of tackling this problem. More efficient logic welcomed. 15 | 16 | 17 | -------------------------------------------------------------------------------- /getTargetSum.py: -------------------------------------------------------------------------------- 1 | # Note this method has O(n) space Complexity and O(n) Time Complexity 2 | def countingSort(array): 3 | dic={} 4 | for i in range(0,len(array)): 5 | if array[i] not in dic: 6 | dic[array[i]]=1 7 | else: 8 | dic[array[i]]+=1 9 | return dic 10 | 11 | def getResult(arrayDic1,arrayDic2,target): 12 | ans=[] 13 | for key in arrayDic1.keys(): 14 | if target_sum-key in arrayDic2: 15 | return True 16 | return False 17 | if __name__=="__main__": 18 | arr1=list(map(int,input().split())) 19 | arr2=list(map(int,input().split())) 20 | target_sum=int(input()) 21 | arrayDic1=countingSort(arr1) 22 | arrayDic2=countingSort(arr2) 23 | print(getResult(arrayDic1,arrayDic2,target_sum)) 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /hashMap/longestConesutiveSequence.cpp: -------------------------------------------------------------------------------- 1 | #define REP(i,a,b) for(int i=a;i& nums) { 5 | if(nums.size()==0)return 0; 6 | setsetArr; 7 | for(auto ele:nums){ 8 | setArr.insert(ele); 9 | } 10 | vectorarr; 11 | for(auto ele:setArr){ 12 | arr.push_back(ele); 13 | } 14 | 15 | int count =1; 16 | int i; 17 | int maxi=INT_MIN; 18 | REP(i,1,arr.size()){ 19 | cout<=0&&x=0&&y>& matrix, int target) { 9 | 10 | int R=matrix.size(); 11 | int C=matrix[0].size(); 12 | 13 | int x=0; 14 | int y=C-1; 15 | 16 | while(1){ 17 | 18 | if(!isValid(R,C,x,y)){ 19 | return false; 20 | } 21 | 22 | if(matrix[x][y]==target){ 23 | break; 24 | } 25 | 26 | if(target 2 | #define MAX 100000 3 | 4 | long long int A[MAX]; 5 | 6 | void get(long long int n){ 7 | long long int i; 8 | for(i=0;iele)u=m-1; 29 | else l=m+1; 30 | } 31 | return -1; 32 | } 33 | 34 | 35 | 36 | int main(){ 37 | long long int n; 38 | scanf("%lld",&n); 39 | get(n); 40 | long long int ele; 41 | scanf("%lld",&ele); 42 | 43 | if(binSearch(n,ele)!=-1){ 44 | printf("%d",binSearch(n,ele)); 45 | } 46 | else{ 47 | printf("\n-1"); 48 | } 49 | 50 | 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /Is Palindrome.cpp: -------------------------------------------------------------------------------- 1 | //head is the head of you linked list 2 | // Following is the node structure 3 | /************** 4 | class node{ 5 | public: 6 | int data; 7 | node * next; 8 | node(int data){ 9 | this->data=data; 10 | this->next=NULL; 11 | } 12 | }; 13 | ***************/ 14 | #define MAX 1000000 15 | typedef struct stack{ 16 | int data[MAX]; 17 | int tos; 18 | }stack; 19 | 20 | 21 | bool check_palindrome(node* head) 22 | { 23 | stack x; 24 | x.tos=-1; 25 | node *p; 26 | p=head; 27 | while(p!=NULL){ 28 | if(x.tos==-1){ 29 | x.data[++x.tos]=p->data; 30 | 31 | } 32 | else{ 33 | if(x.data[x.tos]==p->data) 34 | x.tos--; 35 | else x.data[++x.tos]=p->data; 36 | 37 | } 38 | p=p->next; 39 | } 40 | if(x.tos==-1)return true; 41 | return false; 42 | //write your code here 43 | } 44 | -------------------------------------------------------------------------------- /Fenwick Trees/tutorial/readme.md: -------------------------------------------------------------------------------- 1 | # Optimization of prefix sum, max-min calculations with some binaries and bitmaskings visualised as a tree. 2 | 3 | _Note : The Fenwick Tree is just an array visualization of a tree data structure_ 4 | 5 | _Intution of twoComplement(x) :_ 6 | 7 | * return x&(-1*x) 😄 😆 if confused try out with samples. 8 | 9 | _Algorithm of `getParent(index)` :_ 10 | 11 | * Find 2's complement of index 12 | * Bitwise AND of the original index and 2's complement of index => (andIndex) 13 | * Subtract index and andIndex found above 14 | 15 | _Algorithm of `getNext(index)` :_ 16 | 17 | * Find 2's complement of index 18 | * Bitwise AND of the original index and 2's complement of index => (andIndex) 19 | * Add index and andIndex found above 20 | 21 | _Note : First initialize the Fenwick Tree with the getNext() then update the Fenwick with the same._ 22 | 23 | _Note : To update the Fenwick Tree use getParent()._ 24 | -------------------------------------------------------------------------------- /Fenwick Trees/readme.md: -------------------------------------------------------------------------------- 1 | ## [Create Sorted Array through Instructions](https://leetcode.com/problems/create-sorted-array-through-instructions/) 2 | 3 | * Intution : 4 | * Think of a brute force solution similar to A Counting Sort Algorithm. 5 | * Can you perform any sort of optimizations, may be including prefix sums? 6 | * Is this optimization the best solution? 7 | * Can you optimize it more implementing a Fenwick Tree? 8 | * Hint : 9 | sum=(sum+ min(getSum(ele-1),getSum(maxi)-getSum(ele))) 10 | 11 | * here maxi is (maximum of the elements present in array)+1 12 | * getSum(ele) : Sum of range of values from 1 to ele (in prefix Count FenTree Array) 13 | * getSum(ele-1) 😆 conclude from above. 14 | 15 | --- 16 | 17 | ## [Range Sum Query](https://leetcode.com/problems/range-sum-query-mutable/) : This is a standard Binary Index Tree / Fenwick Tree Problem. 😄 18 | 19 | --- 20 | -------------------------------------------------------------------------------- /missingKnaturalNumbers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | std::setarr; 9 | 10 | 11 | void insert(long long n){ 12 | while (n!=0){ 13 | long long ele; 14 | std::cin>>ele; 15 | if(ele>0){ 16 | arr.insert(ele); 17 | } 18 | n--; 19 | } 20 | } 21 | 22 | void printSet(){ 23 | for(set::iterator i=arr.begin();i!=arr.end();i++)std::cout<<*i<<"\t"; 24 | 25 | } 26 | 27 | void missingKnaturalNumbers(int k){ 28 | unsigned long long i=1; 29 | 30 | while(k!=0){ 31 | if(!binary_search(arr.begin(),arr.end(),i)){ 32 | std::cout<>n; 42 | insert(n); 43 | // printSet(); 44 | int k ; std::cin>>k; 45 | missingKnaturalNumbers(k); 46 | return 0; 47 | } -------------------------------------------------------------------------------- /Dynamic Programming/uniqueBST.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | typedef unsigned long long ll; 3 | using namespace std; 4 | #define REP(i,a,b) for(ll i=a;i&catlans){ 8 | catlans={1,1}; 9 | 10 | ll i; 11 | 12 | REP(i,2,MAX){ 13 | ll j; 14 | ll sum=0; 15 | REP(j,1,i+1){ 16 | sum+=catlans[j-1]*catlans[i-j]; 17 | 18 | } 19 | catlans.push_back(sum); 20 | } 21 | 22 | } 23 | 24 | void printCatlans(vector&catlans){ 25 | cout<<"\nCatlan Numbers are: "; 26 | for(auto ele:catlans){ 27 | cout<>t; 35 | vectorcatlans; 36 | getCatlanNumber(catlans); 37 | //printCatlans(catlans); 38 | while(t--){ 39 | ll n;cin>>n; 40 | cout<>Q; 8 | Q.pushb(mp(root,1)); 9 | 10 | while(!Q.empty()){ 11 | int depth=Q.front().second; 12 | TreeNode * front=Q.front().first; 13 | Q.popf(); 14 | if(front->left!=NULL){ 15 | Q.pushb(mp(front->left,depth+1)); 16 | } 17 | if(front->right!=NULL){ 18 | Q.pushb(mp(front->right,depth+1)); 19 | } 20 | if(front->left==front->right && front->left==NULL){ 21 | if(maxi<=depth)maxi=depth; 22 | } 23 | 24 | } 25 | return maxi; 26 | } 27 | 28 | int maxDepth(TreeNode* root) { 29 | if(root==NULL)return 0; 30 | int maxi=INT_MIN; 31 | 32 | return BFS(root,maxi); 33 | } 34 | }; -------------------------------------------------------------------------------- /UnivalSubtrees.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | 13 | 14 | 15 | bool checkUnival(TreeNode * root,int &count){ 16 | if(root==NULL)return true; 17 | bool left=checkUnival(root->left,count); 18 | bool right=checkUnival(root->right,count); 19 | 20 | if(left==false || right==false)return false; 21 | 22 | if(root->left!=NULL && root->left->val!=root->val)return false; 23 | if(root->right!=NULL && root->right->val!=root->val)return false; 24 | 25 | count++; 26 | return true; 27 | 28 | 29 | } 30 | 31 | bool isUnivalTree(TreeNode* root) { 32 | int count=0; 33 | bool ans= checkUnival(root,count); 34 | // cout<target: 11 | u=m-1 12 | else: 13 | l=m+1 14 | return -1 15 | 16 | 17 | class Solution: 18 | def searchRange(self, nums: List[int], target: int) -> List[int]: 19 | if binSearch(nums,target)==-1: 20 | return [-1,-1] 21 | else: 22 | m=binSearch(nums,target) 23 | j=m 24 | i=m 25 | print(m) 26 | while i>=0: 27 | if nums[i]!=target: 28 | break 29 | i=i-1 30 | 31 | while j>Q; 12 | Q.pushb(mp(root,1)); 13 | 14 | while(!Q.empty()){ 15 | int depth=Q.front().second; 16 | TreeNode * front=Q.front().first; 17 | Q.popf(); 18 | if(front->left!=NULL){ 19 | Q.pushb(mp(front->left,depth+1)); 20 | } 21 | if(front->right!=NULL){ 22 | Q.pushb(mp(front->right,depth+1)); 23 | } 24 | if(front->left==front->right && front->left==NULL){ 25 | if(mini>=depth)mini=depth; 26 | } 27 | 28 | } 29 | return mini; 30 | } 31 | 32 | int minDepth(TreeNode* root) { 33 | if(root==NULL)return 0; 34 | int mini=INT_MAX; 35 | 36 | return BFS(root,mini); 37 | } 38 | }; -------------------------------------------------------------------------------- /Design Problems/hashset.c: -------------------------------------------------------------------------------- 1 | #define MAX 1000000 2 | #define REP(i,a,b) for(int i=a;iarr[i]=0; // Not Present 17 | } 18 | return p; 19 | } 20 | 21 | void myHashSetAdd(MyHashSet* p, int key) { 22 | p->arr[key]=1; 23 | } 24 | 25 | void myHashSetRemove(MyHashSet* p, int key) { 26 | p->arr[key]=0; 27 | } 28 | 29 | /** Returns true if this set contains the specified element */ 30 | bool myHashSetContains(MyHashSet* obj, int key) { 31 | if(obj->arr[key])return true; 32 | return false; 33 | } 34 | 35 | void myHashSetFree(MyHashSet* obj) { 36 | free(obj); 37 | } 38 | 39 | /** 40 | * Your MyHashSet struct will be instantiated and called as such: 41 | * MyHashSet* obj = myHashSetCreate(); 42 | * myHashSetAdd(obj, key); 43 | 44 | * myHashSetRemove(obj, key); 45 | 46 | * bool param_3 = myHashSetContains(obj, key); 47 | 48 | * myHashSetFree(obj); 49 | */ -------------------------------------------------------------------------------- /odd_even_link_list_o(n).c: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * struct ListNode *next; 6 | * }; 7 | */ 8 | 9 | 10 | struct ListNode* oddEvenList(struct ListNode* head){ 11 | struct ListNode *preptr,*ptr,*postptr,*tmp1,*tmp2,*tmp3,*temp; 12 | int cnt; 13 | if (head==NULL || head->next==NULL || head->next->next==NULL) 14 | { 15 | return head; 16 | } 17 | preptr=head; 18 | ptr=head->next; 19 | postptr=ptr->next; 20 | while(postptr!=NULL) 21 | { 22 | tmp1=postptr->next; 23 | tmp2=ptr->next; 24 | tmp3=preptr->next; 25 | preptr->next=tmp2; 26 | postptr->next=tmp3; 27 | ptr->next=tmp1; 28 | postptr=ptr; 29 | cnt=0; 30 | preptr=preptr->next; 31 | while(postptr!=NULL && cnt<2) 32 | { 33 | ptr=postptr; 34 | postptr=postptr->next; 35 | cnt++; 36 | } 37 | } 38 | // temp=head; 39 | // while(temp!=NULL) 40 | // { 41 | // printf("%d ",temp->val); 42 | // temp=temp->next; 43 | // } 44 | return head; 45 | } 46 | 47 | -------------------------------------------------------------------------------- /twoPointers/longestSubstringWithoutRepeatingCharacters.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lengthOfLongestSubstring(string s) { 4 | dequeQ; 5 | mapdic; 6 | int count=0; 7 | int maxi=0; 8 | 9 | for(auto ele:s){ 10 | 11 | if(dic[ele]==false){ 12 | Q.push_back(ele); 13 | dic[ele]=true; 14 | count++; 15 | } 16 | else{ 17 | 18 | 19 | while(!Q.empty()){ 20 | char front=Q.front(); 21 | dic[front]=false; 22 | Q.pop_front(); 23 | count--; 24 | if(front==ele){ 25 | Q.push_back(ele); 26 | dic[ele]=true; 27 | count++; 28 | break; 29 | } 30 | } 31 | 32 | 33 | } 34 | maxi=max(maxi,count); 35 | 36 | } 37 | maxi=max(maxi,count); 38 | return maxi; 39 | 40 | } 41 | }; -------------------------------------------------------------------------------- /linkedList/mergeKsortedLists.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode* mergeKLists(vector& lists) { 12 | 13 | priority_queue,greater>Q; 14 | for(auto ele:lists){ 15 | ListNode *q=ele; 16 | while(q!=NULL){ 17 | //cout<val<<" "; 18 | Q.push(q->val); 19 | q=q->next; 20 | 21 | } 22 | } 23 | ListNode *soltn=NULL; 24 | ListNode *tail=NULL; 25 | while(!Q.empty()){ 26 | ListNode *newNode=new ListNode(); 27 | newNode->val=Q.top(); 28 | newNode->next=NULL; 29 | if(soltn==NULL){ 30 | soltn=newNode; 31 | tail=newNode; 32 | 33 | } 34 | else{ 35 | tail->next=newNode; 36 | tail=tail->next; 37 | } 38 | //cout< 2 | using namespace std; 3 | typedef long long ll; 4 | #define REP(i,a,b) for(ll i=a;i prices, int opp) { 7 | ll transactions=opp; 8 | ll n=prices.size(); 9 | 10 | if(n==0)return 0; // This is to get the corner case with no input 11 | 12 | vectorpreRow(n,0); 13 | vector>profit(transactions+1,preRow); 14 | 15 | 16 | ll i; 17 | 18 | REP(i,1,transactions+1){ 19 | ll j; 20 | REP(j,1,n){ 21 | ll k; 22 | ll index=0; 23 | ll maxi=INT_MIN; 24 | 25 | REP(k,0,j){ 26 | if(maxi<(prices[j]-prices[k]+profit[i-1][k])){ 27 | maxi=(prices[j]-prices[k]+profit[i-1][k]); 28 | } 29 | } 30 | 31 | profit[i][j]=max(profit[i][j-1 ],maxi); 32 | 33 | } 34 | } 35 | 36 | /*for(auto each:profit){ 37 | for(auto every:each){ 38 | cout<next==NULL)return head; 17 | 18 | ListNode *i;ListNode *j;ListNode *preI;ListNode *t; 19 | 20 | i=head; 21 | j=head->next; 22 | head=j; 23 | 24 | while(i->next!=NULL){ 25 | 26 | t=j->next; 27 | j->next=i; 28 | i->next=t; 29 | preI=i; 30 | i=i->next; 31 | 32 | if(i!=NULL){ 33 | j=i->next; 34 | preI->next=j; 35 | } 36 | else{ 37 | preI->next=i; 38 | break; 39 | } 40 | 41 | 42 | } 43 | // If list has odd number of nodes -- 44 | if(j==NULL){ 45 | preI->next=i; 46 | } 47 | return head; 48 | 49 | 50 | 51 | } 52 | }; -------------------------------------------------------------------------------- /Dynamic Programming/Move_to_other_end.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | L=[] 3 | n=int(input("Enter Dimensions of chessboard: ")) 4 | for i in range(0,n): 5 | if i==0: 6 | 7 | L.append(list(map(int,"1"*n))) 8 | else: 9 | L.append(list(map(int,"0"*n))) 10 | 11 | for i in range(0,n): 12 | L[i][0]=1 13 | L=np.array(L) 14 | print("BEFORE : \n", L) 15 | 16 | i=1 17 | while ival>=val){ 22 | if(p->left==NULL){ 23 | p->left=node; 24 | return root; 25 | } 26 | p=p->left; 27 | } 28 | else{ 29 | 30 | if(p->right==NULL){ 31 | p->right=node; 32 | return root; 33 | } 34 | p=p->right; 35 | 36 | 37 | } 38 | 39 | } 40 | 41 | return root; 42 | 43 | } 44 | }; -------------------------------------------------------------------------------- /twoPointers/readme.md: -------------------------------------------------------------------------------- 1 | # Point to different indices and feel more powerful!! 2 | 3 | #### CONTAINER WITH MOST WATER (REAL LIFE): 4 | 5 | *Link to problem :* [Leetocode](https://leetcode.com/problems/container-with-most-water/) 6 | 7 | *Algorithm:* 8 | 9 | 1. In the provided list of values place two pointers i,j such that both of them lies in extreme corners of the list. 10 | 2. Calculate area as: 11 | Area=Width*Height 12 | Width=(j-i) 13 | Height=min(height[j],height[i]) 14 | 3. Look for maximum of the obtained area. 15 | 4. Change the values of i and j greedily. 16 | 5. Return maximum area obtained. 17 | 18 | *** 19 | 20 | #### Longest Substring Without Repeating Characters 21 | 22 | *Link to problem :*[Leetcode](https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/579/week-1-january-1st-january-7th/3595/) 23 | 24 | *Algorithm:* 25 | 26 | 1. Try to think of a two pointer based solution. 27 | 2. One pointer pointer placed at end of current String and maintain each character in current string using hashmap. 28 | 3. Can you minimize use of Two pointers with an equivalent Data Structure (Hint : Linear Data Structure?). 29 | 4. Time Complexity : O(n) 30 | 5. Space Complexity : O(n) 31 | 32 | -------------------------------------------------------------------------------- /Design Problems/hashmap.c: -------------------------------------------------------------------------------- 1 | #define MAX 1000000 2 | #define REP(i,a,b) for(int i=a;iarr[i]=-1; 15 | } 16 | return p; 17 | } 18 | 19 | /** value will always be non-negative. */ 20 | void myHashMapPut(MyHashMap* p, int key, int value) { 21 | p->arr[key]=value; 22 | } 23 | 24 | /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */ 25 | int myHashMapGet(MyHashMap* obj, int key) { 26 | return obj->arr[key]; 27 | } 28 | 29 | /** Removes the mapping of the specified value key if this map contains a mapping for the key */ 30 | void myHashMapRemove(MyHashMap* obj, int key) { 31 | obj->arr[key]=-1; 32 | 33 | } 34 | 35 | void myHashMapFree(MyHashMap* obj) { 36 | free(obj); 37 | } 38 | 39 | /** 40 | * Your MyHashMap struct will be instantiated and called as such: 41 | * MyHashMap* obj = myHashMapCreate(); 42 | * myHashMapPut(obj, key, value); 43 | 44 | * int param_2 = myHashMapGet(obj, key); 45 | 46 | * myHashMapRemove(obj, key); 47 | 48 | * myHashMapFree(obj); 49 | */ -------------------------------------------------------------------------------- /Dynamic Programming/k-palindrome.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | bool is_k_palin(string s,int k); 6 | 7 | int main() { 8 | // your code goes here 9 | int t; 10 | cin>>t; 11 | while(t--) 12 | { 13 | string s ; 14 | cin>>s; 15 | int k; 16 | cin>>k; 17 | 18 | cout<=b;i--) 25 | 26 | /*You are required to complete this function*/ 27 | bool is_k_palin(string s,int k) 28 | { int size=s.size(); 29 | string reverse; 30 | vector>table; 31 | vectorperRow(size+1,0); 32 | 33 | int i; 34 | 35 | REPI(i,size-1,0)reverse+=s[i]; 36 | 37 | REP(i,0,size+1)table.push_back(perRow); 38 | 39 | REP(i,1,size+1){ 40 | int j; 41 | REP(j,1,size+1){ 42 | if(s[i-1]==reverse[j-1]){ 43 | table[i][j]=table[i-1][j-1]+1; 44 | 45 | } 46 | else{ 47 | table[i][j]=max(table[i-1][j],table[i][j-1]); 48 | } 49 | } 50 | } 51 | 52 | 53 | if(size-table[size][size]<=k)return true; 54 | return false; 55 | 56 | 57 | 58 | 59 | //Your code here 60 | } -------------------------------------------------------------------------------- /merge_two_sorted_list.c: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * struct ListNode *next; 6 | * }; 7 | */ 8 | 9 | #include 10 | 11 | 12 | struct ListNode * insertEnd(struct ListNode *head,int ele){ 13 | struct ListNode *p=(struct ListNode *)malloc(sizeof(struct ListNode)); 14 | p->val=ele; 15 | p->next=NULL; 16 | 17 | if(head==NULL){ 18 | head =p; 19 | return head; 20 | } 21 | struct ListNode *q=head; 22 | while(q->next!=NULL)q=q->next; 23 | q->next=p; 24 | return head; 25 | 26 | } 27 | 28 | 29 | struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){ 30 | struct ListNode * start=NULL; 31 | 32 | while(l1!=NULL && l2!=NULL){ 33 | if(l1->val<=l2->val){ 34 | start=insertEnd(start,l1->val); 35 | l1=l1->next; 36 | 37 | } 38 | else{ 39 | start=insertEnd(start,l2->val); 40 | l2=l2->next; 41 | } 42 | 43 | } 44 | 45 | while(l1!=NULL){ 46 | start=insertEnd(start,l1->val); 47 | l1=l1->next; 48 | } 49 | 50 | while(l2!=NULL){ 51 | start=insertEnd(start,l2->val); 52 | l2=l2->next; 53 | } 54 | 55 | return start; 56 | 57 | } 58 | 59 | -------------------------------------------------------------------------------- /Dynamic Programming/longestPalindromicSubsequence.cpp: -------------------------------------------------------------------------------- 1 | #define REP(i,a,b) for(int i=a;i>&table,int size){ 5 | int i; 6 | REP(i,0,size+1){ 7 | vectorchild; 8 | int j; 9 | REP(j,0,size+1){ 10 | child.push_back(0); 11 | } 12 | table.push_back(child); 13 | } 14 | } 15 | 16 | int LCS(vector>&table,string x ,string y,int size){ 17 | int i; 18 | REP(i,1,size+1){ 19 | int j; 20 | REP(j,1,size+1){ 21 | if(x[i-1]==y[j-1]){ 22 | table[i][j]=table[i-1][j-1]+1; 23 | } 24 | else{ 25 | table[i][j]=max(table[i-1][j],table[i][j-1]); 26 | } 27 | } 28 | } 29 | return table[size][size]; 30 | 31 | } 32 | 33 | int longestPalindromeSubseq(string s) { 34 | int size=s.size(); 35 | string reversed=""; 36 | int i=size-1; 37 | while(i>=0){ 38 | reversed+=s[i]; 39 | i--; 40 | } 41 | 42 | 43 | vector>table; 44 | fillTable(table,size); 45 | return LCS(table,s,reversed,size); 46 | 47 | } 48 | }; -------------------------------------------------------------------------------- /Dynamic Programming/longestValidParenthesis.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define REP(i,a,b) for(int i=a;i>stk; 12 | vectorvis(size,0); 13 | 14 | REP(i,0,size){ 15 | if(s[i]=='('){ 16 | stk.push({'(',i}); 17 | } 18 | else{ 19 | 20 | if(!stk.empty()){ 21 | pairstkTop=stk.top(); 22 | stk.pop(); 23 | vis[i]=1; 24 | vis[stkTop.second]=1; 25 | } 26 | 27 | } 28 | } 29 | 30 | 31 | int count=0; 32 | // cout<<"Vis :"; 33 | // for(auto ele:vis){ 34 | // cout<g++ interview.cpp -o a.exe 4 | 5 | D:\C++ FILES>a 6 | Enter number of Elements in Linked List : 10 7 | 8 | Enter data : 1 9 | 10 | 11 | List Obtained : 1 12 | 13 | Enter data : 2 14 | 15 | 16 | List Obtained : 1 2 17 | 18 | Enter data : 3 19 | 20 | 21 | List Obtained : 1 2 3 22 | 23 | Enter data : 4 24 | 25 | 26 | List Obtained : 1 2 3 4 27 | 28 | Enter data : 5 29 | 30 | 31 | List Obtained : 1 2 3 4 5 32 | 33 | Enter data : 6 34 | 35 | 36 | List Obtained : 1 2 3 4 5 6 37 | 38 | Enter data : 7 39 | 40 | 41 | List Obtained : 1 2 3 4 5 6 7 42 | 43 | Enter data : 8 44 | 45 | 46 | List Obtained : 1 2 3 4 5 6 7 8 47 | 48 | Enter data : 9 49 | 50 | 51 | List Obtained : 1 2 3 4 5 6 7 8 9 52 | 53 | Enter data : 10 54 | 55 | 56 | List Obtained : 1 2 3 4 5 6 7 8 9 10 57 | 58 | Middle element: 5 59 | 60 | First List obtained : 61 | 62 | List Obtained : 6 7 8 9 10 63 | 64 | Second List obtained : 65 | 66 | List Obtained : 1 2 3 4 5 67 | 68 | After Shuffling: 69 | 70 | List Obtained : 6 1 7 2 8 3 9 4 10 5 71 | -------------------------------------------------------------------------------- /Union Find/readme.md: -------------------------------------------------------------------------------- 1 | ## Union Find implements Disjoint Set Units data structures here with Speghatti Stack implementation. 2 | 3 | --- 4 | 5 | ## [Accounts-Merge](https://leetcode.com/problems/accounts-merge/) 6 | 7 | * Intution : 8 | * The problem seems to be simply a graph traversal. 9 | * Other way to visualize is implementing DSU to maintain transitivity. 10 | * Think of a username to be a node and email to be other node with different structures (C/C++) 😆 specific. 11 | * Now try to merge the two emailIDs belonging to users having same emailIDs. 12 | * Remember separate hashmaps are used to maintain whether a emailID exists or not with any user. 13 | 14 | _Note : Two or more users may be merged think of a logic in linear time to merge the users with similar emailID and remove either of the user(condition mentioned username remains same)._ 15 | 16 | * To return the result maintain set of string and fullfill requirements. 17 | 18 | *** 19 | 20 | ## [Couples Holding Hands](https://leetcode.com/problems/couples-holding-hands/) 21 | 22 | * Intutuion : 23 | * Consider all couples to be nodes with next pointer initially pointing to NULL. 24 | * For every adjacent pairs of seats connect the nodes with each other. 25 | * Try to check if the condition matches for couples as mentioned using union and find , use a counter variable to count the number of swaps. 26 | * return swaps. 27 | 28 | *** -------------------------------------------------------------------------------- /Fenwick Trees/Count_of_Smaller_Numbers_After_Self.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define REP(i,a,b) for(int i=a;i 5 | 6 | class Solution { 7 | public: 8 | 9 | const int MAX=1e+4+1; 10 | 11 | unordered_mapBIT; 12 | 13 | 14 | int twoComplement(int n){ 15 | return n&-n; 16 | } 17 | int getParent(int n){ 18 | return n-twoComplement(n); 19 | } 20 | int getNext(int n){ 21 | return n+twoComplement(n); 22 | } 23 | 24 | void update(int n){ 25 | 26 | while(n<=2*MAX){ 27 | BIT[n]++; 28 | n=getNext(n); 29 | } 30 | 31 | } 32 | 33 | int query(int n){ 34 | int sum=0; 35 | while (n>0) 36 | { 37 | sum+=BIT[n]; 38 | n=getParent(n); 39 | /* code */ 40 | } 41 | return sum; 42 | } 43 | 44 | vector countSmaller(vector& nums) { 45 | 46 | int size=nums.size(); 47 | 48 | int i=size-1; 49 | vectorans; 50 | 51 | while (i>=0) 52 | { 53 | nums[i]+=MAX; 54 | ans.push_back(query(nums[i]-1)); 55 | 56 | update(nums[i]); 57 | 58 | 59 | i--; 60 | /* code */ 61 | } 62 | 63 | reverse(ans.begin(),ans.end()); 64 | 65 | return ans; 66 | 67 | 68 | } 69 | }; -------------------------------------------------------------------------------- /hashMap/readme.md: -------------------------------------------------------------------------------- 1 | 2 |
Maps that allows you hash stuff together!! 😄
3 |
4 | Longest Fibonacci Subsequence : G4G 5 |
6 | Intution: 7 |
    8 |
  1. Pecompute a bitmap for every Fib term . 9 |
  2. Map the input with the bitmap obtained and print the output if the input exists in the bitmap.
  3. 10 |
11 |
12 | 13 | #### Longest Consecutive Sequence 14 | 15 | ###### Link to problem 👍 [Leetcode](https://leetcode.com/problems/longest-consecutive-sequence/) 16 | 17 | ##### Intution: 18 | 1. Try to minimize the array-size by removing similar elements and sort the given array. 19 | 2. Can you index the elements present in the set to directly refer them anyhow? 20 | 3. Hash and maintain a flag to check which element exists (a typical intution of Counting Sort Algorithm) or simply iterate that set to form a new vector. 21 | 4. Initialize maxii (maximum consecutive counter) to INT_MIN to get the maximum consecutive size of Longest Consecutive Sequence. 22 | 4. For every index in the array/vector (1:vector.size()) check whether the previous element is predecessor or not . 23 | 4. If "YES" : increment the counter. 24 | 5. Otherwise reinitialize value of maxii to counter and reinitialize counter to 1. 25 | 6. Return maxii (maximum consecutive counter). 26 | 27 | **** 28 | -------------------------------------------------------------------------------- /runLengthEncoding.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | typedef long long ll; 3 | 4 | using namespace std; 5 | 6 | void encode(string); 7 | void decode(string); 8 | 9 | 10 | int main() { 11 | ll choice ;cin>>choice;fflush(stdin);fflush(stdout); 12 | string s;cin>>s; 13 | 14 | switch(choice){ 15 | case 1: 16 | encode(s); 17 | break; 18 | case 2: 19 | decode(s); 20 | 21 | break; 22 | 23 | 24 | 25 | } 26 | 27 | return 0; 28 | } 29 | 30 | void encode(string s){ 31 | 32 | for(int i=0;s[i];){ 33 | int j=i; 34 | int count=0; 35 | for(;s[j];j++){ 36 | if(s[i]!=s[j])break; 37 | count ++; 38 | } 39 | cout< 9 | 10 | struct ListNode* insertEnd(struct ListNode *head,int ele){ 11 | struct ListNode *p; 12 | p=head; 13 | struct ListNode *node=(struct ListNode *)malloc(sizeof(struct ListNode)); 14 | node->val=ele; 15 | // printf("Value: %d ",node->val); 16 | node->next=NULL; 17 | if(p==NULL){ 18 | head=node; 19 | 20 | return head; 21 | } 22 | while(p->next!=NULL)p=p->next; 23 | p->next=node; 24 | 25 | return head; 26 | 27 | } 28 | 29 | void printList(struct ListNode *head){ 30 | struct ListNode*p=head; 31 | while(p!=NULL){ 32 | printf("%d ",p->val); 33 | p=p->next; 34 | } 35 | printf("\n"); 36 | 37 | } 38 | 39 | struct ListNode* oddEvenList(struct ListNode* head){ 40 | if(head==NULL)return NULL; 41 | 42 | struct ListNode *p; 43 | p=head; 44 | int c=0; 45 | struct ListNode *even=NULL; 46 | struct ListNode *odd=NULL; 47 | 48 | 49 | while(p!=NULL){ 50 | if(c%2==0) even= insertEnd(even,p->val); 51 | else odd=insertEnd(odd,p->val); 52 | c++; 53 | // printf("%lld %lld\n",even,odd); 54 | p=p->next; 55 | } 56 | 57 | printList(even); 58 | printList(odd); 59 | 60 | 61 | struct ListNode *evenstart=even; 62 | while(evenstart->next!=NULL)evenstart=evenstart->next; 63 | evenstart->next=odd; 64 | evenstart=even; 65 | 66 | printList(evenstart); 67 | 68 | return evenstart; 69 | } 70 | 71 | -------------------------------------------------------------------------------- /Tree Algorithms/maxLevelSumOfBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | #define pushb push_back 13 | #define popb pop_back 14 | #define popf pop_front 15 | class Solution { 16 | public: 17 | int maxLevelSum(TreeNode* root) { 18 | if(root==NULL){return 0;} 19 | deque>Q; 20 | Q.pushb({root}); 21 | int index=0; 22 | int maxii=INT_MIN; 23 | int level=0; 24 | int pos=-1; 25 | while(!Q.empty()){ 26 | dequefrontQ=Q.front(); 27 | dequechild; 28 | Q.popf(); 29 | int sum=0; 30 | while(!frontQ.empty()){ 31 | TreeNode * fr=frontQ.front(); 32 | sum+=fr->val; 33 | frontQ.popf(); 34 | if(fr->left!=NULL){ 35 | child.pushb(fr->left); 36 | } 37 | if(fr->right!=NULL){ 38 | child.pushb(fr->right); 39 | } 40 | } 41 | if(!child.empty()){ 42 | Q.pushb(child); 43 | } 44 | //cout< 3 | #define vvi vector 4 | #define vvvi vector 5 | 6 | 7 | class Solution { 8 | public: 9 | int MOD = 1e9 + 7; 10 | int dp[52][52][52]={-1}; 11 | 12 | bool isValid(int r,int c,int x,int y){ 13 | if(x>=0&&x=0&&y 2 | #define MAX 1001 3 | using namespace std; 4 | #define REP(i,a,b) for(int i=a;iLCS; 23 | 24 | while(i>=1 && j>=1){ 25 | 26 | if(x[i-1]==y[j-1]){ 27 | LCS.push(x[i-1]); 28 | i--; 29 | j--; 30 | } 31 | else{ 32 | if(table[i-1][j]>table[i][j-1]){ 33 | i--; 34 | } 35 | else{ 36 | j--; 37 | } 38 | } 39 | 40 | } 41 | 42 | string soltn=""; 43 | 44 | while(!LCS.empty()){ 45 | soltn+=LCS.top(); 46 | LCS.pop(); 47 | } 48 | 49 | cout<<"LCS is : "<>x>>y; 83 | fillTable(x,y); 84 | 85 | 86 | 87 | return 0; 88 | } -------------------------------------------------------------------------------- /FindMedianFromDataStream.cpp: -------------------------------------------------------------------------------- 1 | typedef long long ll; 2 | 3 | class MedianFinder { 4 | public: 5 | /** initialize your data structure here. */ 6 | priority_queuemaxHeap; 7 | priority_queue,greater>minHeap; 8 | ll sizeMinHeap=0; 9 | ll sizeMaxHeap=0; 10 | 11 | MedianFinder() { 12 | maxHeap={}; 13 | minHeap={}; 14 | sizeMinHeap=0; 15 | sizeMaxHeap=0; 16 | } 17 | 18 | void balance(){ 19 | ll t; 20 | if(sizeMaxHeap+2==sizeMinHeap){ 21 | t=minHeap.top(); 22 | minHeap.pop(); 23 | maxHeap.push(t); 24 | sizeMaxHeap++; 25 | sizeMinHeap--; 26 | } 27 | else if(sizeMinHeap+2==sizeMaxHeap){ 28 | t=maxHeap.top(); 29 | maxHeap.pop(); 30 | minHeap.push(t); 31 | sizeMaxHeap--; 32 | sizeMinHeap++; 33 | } 34 | } 35 | 36 | void addNum(int num) { 37 | if(sizeMaxHeap==0){ 38 | maxHeap.push(num); 39 | sizeMaxHeap++; 40 | } 41 | else{ 42 | if(maxHeap.top()>=num){maxHeap.push(num);sizeMaxHeap++;} 43 | else {minHeap.push(num);sizeMinHeap++; } 44 | } 45 | balance(); 46 | 47 | } 48 | 49 | double findMedian() { 50 | if(sizeMaxHeap==sizeMinHeap)return (double) (maxHeap.top()+minHeap.top())/2; 51 | if(sizeMaxHeap>sizeMinHeap)return (double) maxHeap.top(); 52 | return (double) minHeap.top(); 53 | } 54 | }; 55 | 56 | /** 57 | * Your MedianFinder object will be instantiated and called as such: 58 | * MedianFinder* obj = new MedianFinder(); 59 | * obj->addNum(num); 60 | * double param_2 = obj->findMedian(); 61 | */ -------------------------------------------------------------------------------- /Dynamic Programming/editDistance.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define MAX 1000 3 | using namespace std; 4 | #define REP(i,a,b) for(int i=a;i>&table,int rows ,int cols){ 7 | 8 | int i; 9 | REP(i,0,rows+1){ 10 | int j; 11 | vectorchild; 12 | REP(j,0,cols+1){ 13 | child.push_back(0); 14 | } 15 | table.push_back(child); 16 | } 17 | 18 | REP(i,0,rows+1){ 19 | table[i][0]=i; 20 | } 21 | REP(j,0,cols+1){ 22 | table[0][j]=j; 23 | } 24 | 25 | // cout<>table,string X,string Y,int rows,int cols){ 31 | //cout<>t; 61 | 62 | while(t--){ 63 | string X,Y;cin>>X>>Y; 64 | int x,y; 65 | x=X.size(); 66 | y=Y.size(); 67 | vector>table; 68 | fillTable(table,x,y); 69 | cout< bool: 4 | stack=[] 5 | for i in range(0,len(s)): 6 | if s[i]=='(' or s[i]=='*': 7 | stack.append(s[i]) 8 | else: 9 | if len(stack)==0 : 10 | return False 11 | stars=0 12 | flag=0 13 | while len(stack)!=0: 14 | 15 | ele=stack[-1] 16 | 17 | stack.pop() 18 | if ele=='*': 19 | stars+=1 20 | if ele=='(': 21 | flag=1 22 | break 23 | 24 | if len(stack)==0 and flag!=1: 25 | 26 | if stars!=0: 27 | stars-=1 28 | while stars!=0: 29 | stack.append('*') 30 | stars-=1 31 | 32 | print(stack) 33 | print("I am out") 34 | stars=0 35 | openb=0 36 | 37 | if(list(set(stack))==['*']): 38 | return True 39 | 40 | while True: 41 | if(len(stack)==0) or (list(set(stack))==['*']): 42 | return True 43 | stars=0 44 | while len(stack)!=0: 45 | ele=stack[-1] 46 | stack.pop() 47 | if ele=='(': 48 | break 49 | stars+=1 50 | 51 | if stars==0: 52 | return False 53 | stars-=1 54 | while stars!=0: 55 | stars-=1 56 | stack.append('*') 57 | 58 | print(stack) 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /Union Find/redundantConnections.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define REP(i,a,b) for(int i=a;i 5 | #define vvi vector 6 | 7 | class Solution { 8 | public: 9 | 10 | const int MAX=1e3; 11 | 12 | typedef struct node{ 13 | 14 | struct node *next; 15 | int val; 16 | 17 | }node; 18 | 19 | unordered_mapnodeDic; 20 | unordered_mapparentDic; 21 | 22 | 23 | void createNode(int val){ 24 | node *newNode=new node; 25 | newNode->next=NULL; 26 | newNode->val=val; 27 | nodeDic[val]=newNode; 28 | parentDic[val]=true; 29 | } 30 | 31 | 32 | node *parent(node *p){ 33 | node *q=p; 34 | while (p->next!=NULL) 35 | { 36 | 37 | p=p->next; 38 | /* code */ 39 | } 40 | 41 | while (q->next!=NULL&&q!=p) 42 | { 43 | node *t=q->next; 44 | q->next=p; 45 | q=t; 46 | 47 | /* code */ 48 | } 49 | 50 | return p; 51 | 52 | 53 | } 54 | 55 | vi ans; 56 | 57 | void merge(int a,int b){ 58 | node *nodeA=nodeDic[a]; 59 | node *nodeB=nodeDic[b]; 60 | node *parentA=parent(nodeA); 61 | node *parentB=parent(nodeB); 62 | 63 | if(parent(nodeA)!=parent(nodeB)){ 64 | 65 | 66 | parentA->next=parentB; 67 | parentDic[a]=false; 68 | parentDic[b]=true; 69 | } 70 | else{ 71 | ans={a,b}; 72 | } 73 | 74 | } 75 | 76 | vector findRedundantConnection(vector>& edges) { 77 | 78 | int i; 79 | REP(i,1,MAX+1){ 80 | createNode(i); 81 | } 82 | 83 | for(auto ele:edges){ 84 | int s=ele[0]; 85 | int d=ele[1]; 86 | merge(s,d); 87 | } 88 | 89 | return ans; 90 | } 91 | }; -------------------------------------------------------------------------------- /Tree Algorithms/binTreeRightSideView.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | #define pushb push_back 13 | #define popf pop_front 14 | 15 | class Solution { 16 | public: 17 | 18 | void bfs(TreeNode *root,deque>&ans){ 19 | deque>arr; 20 | arr.pushb({root}); 21 | ans.pushb({root->val}); 22 | 23 | while(!arr.empty()){ 24 | vectorchild=arr.front(); 25 | arr.popf(); 26 | vectorinsertChild; 27 | vectorchildAns; 28 | for(auto ele:child){ 29 | if(ele->left!=NULL){ 30 | insertChild.pushb(ele->left); 31 | childAns.pushb(ele->left->val); 32 | } 33 | if(ele->right!=NULL){ 34 | insertChild.pushb(ele->right); 35 | childAns.pushb(ele->right->val); 36 | } 37 | 38 | } 39 | if(!insertChild.empty()) 40 | { arr.pushb(insertChild); 41 | ans.pushb(childAns); 42 | } 43 | 44 | } 45 | 46 | 47 | } 48 | 49 | vector rightSideView(TreeNode* root) { 50 | if(root==NULL)return {}; 51 | deque>ans; 52 | bfs(root,ans); 53 | vectorsoltn; 54 | for(auto each:ans){ 55 | soltn.pushb(*each.rbegin()); 56 | /*for(auto every:each){ 57 | cout< 2 | using namespace std; 3 | #define fastIO ios_base::sync_with_stdio(false);cin.tie(NULL); 4 | #define pii pair 5 | #define vi vector 6 | #define mii map 7 | #define umii unordered_map 8 | #define dqi deque 9 | #define pqL priority_queue,less> 10 | #define pqG priority_queue,greater> 11 | #define REP(i,a,b) for(int i=a;idic; 23 | 24 | void init(int i){ 25 | node *newNode= new node; 26 | newNode->next=NULL; 27 | newNode->val=i; 28 | dic[i]=newNode; 29 | } 30 | 31 | int minSwapsCouples(vector& row) { 32 | int maxi=*max_element(row.begin(),row.end()); 33 | int i; 34 | REP(i,0,maxi+1){ 35 | //cout<<"val :"<next=nodeB; 45 | nodeB->next=nodeA; 46 | i++; 47 | i++; 48 | } 49 | 50 | i=0; 51 | int count=0; 52 | while(i<=maxi){ 53 | node *nodeA=dic[i]; 54 | node *nodeB=nodeA->next; 55 | if(nodeA->val+1!=nodeB->val){ 56 | node *nodeC=dic[i+1]; 57 | node *nodeD=nodeC->next; 58 | nodeA->next=nodeC; 59 | nodeB->next=nodeD; 60 | nodeD->next=nodeB; 61 | count++; 62 | } 63 | i++; 64 | i++; 65 | } 66 | return count; 67 | 68 | } 69 | }; 70 | 71 | int main(){ 72 | fastIO 73 | vectorrow; 74 | int n; 75 | cin>>n; 76 | int i; 77 | REP(i,0,n){ 78 | int ee; 79 | cin>>ee; 80 | row.push_back(ee); 81 | } 82 | 83 | 84 | Solution *obj=new Solution; 85 | cout<<"Answer :"<minSwapsCouples(row); 86 | return 0; 87 | } -------------------------------------------------------------------------------- /linkedList/swapNodesInkGroup.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | 12 | ListNode *satisfies(ListNode *head,int k){ 13 | int count=1; 14 | ListNode *p=head; 15 | 16 | while(p!=NULL && count!=k){ 17 | p=p->next;count++; 18 | } 19 | if(count==k)return p; 20 | return NULL; 21 | 22 | } 23 | 24 | ListNode *reverseList(ListNode *start,ListNode *end){ 25 | ListNode *pre=NULL; 26 | ListNode *p=start; 27 | while(p!=end){ 28 | ListNode *t=p->next; 29 | p->next=pre; 30 | pre=p; 31 | p=t; 32 | } 33 | p->next=pre; 34 | return p; 35 | } 36 | 37 | 38 | 39 | ListNode* reverseKGroup(ListNode* head, int k) { 40 | if(head==NULL)return NULL; 41 | if(k==1)return head; 42 | ListNode *p=head;int i=0; 43 | ListNode *pre=NULL; 44 | 45 | 46 | while(1){ 47 | 48 | ListNode *endKth=satisfies(p,k); 49 | 50 | if(endKth==NULL){ 51 | if(pre==NULL)return head; 52 | pre->next=p; 53 | return head; 54 | } 55 | else{ 56 | 57 | ListNode *t=endKth->next; 58 | ListNode *newHead=reverseList(p,endKth); 59 | 60 | if(i==0){ 61 | 62 | head=newHead; 63 | i++; 64 | pre=p; 65 | p=t; 66 | 67 | } 68 | else{ 69 | 70 | if(newHead!=p){ 71 | pre->next=newHead; 72 | pre=p; 73 | p=t; 74 | i++; 75 | 76 | } 77 | else{ 78 | 79 | pre->next=p; 80 | return head; 81 | } 82 | } 83 | } 84 | } 85 | return head; 86 | } 87 | }; -------------------------------------------------------------------------------- /Fenwick Trees/createSortedArrayThroughInstructions.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define vi vector 4 | #define vll vector 5 | typedef long long ll; 6 | #define REP(i, a, b) for (int i = a; i < b; i++) 7 | #define MOD 1000000007 8 | 9 | 10 | 11 | 12 | class Solution 13 | { 14 | public: 15 | int fenTree[1000000]={0}; 16 | 17 | 18 | 19 | 20 | void printFenTree(vll arr){ 21 | cout<<"FenTree is :"; 22 | for(auto ele:arr){ 23 | cout< 0) 69 | { 70 | sum += fenTree[fenIndex]; 71 | fenIndex = getParent(fenIndex); 72 | } 73 | 74 | return sum; 75 | } 76 | 77 | int createSortedArray(vector &instructions) 78 | { 79 | 80 | int maxi = *max_element(instructions.begin(), instructions.end()); 81 | 82 | vll fenTree(maxi + 2, 0); 83 | int size=maxi+2; 84 | long long int sum = 0; 85 | 86 | for (auto ele : instructions) 87 | { 88 | 89 | //printFenTree(fenTree); 90 | sum = (sum+min(getSumFenTree(ele-1), getSumFenTree(maxi) - getSumFenTree(ele)))%MOD; 91 | 92 | updateFenTree(ele, maxi,size); 93 | } 94 | 95 | return sum; 96 | } 97 | }; 98 | -------------------------------------------------------------------------------- /Tree Algorithms/binTreeZigZagLevelOrderTraversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | #define pushb push_back 13 | #define popf pop_front 14 | #define vi vector 15 | #define di deque 16 | #define dvi deque> 17 | #define vvi vector> 18 | #define REP(i,a,b) for(int i=a;i> Q; 25 | Q.pushb({root}); 26 | 27 | vvi soltn={{root->val}}; 28 | 29 | while(!Q.empty()){ 30 | dequefront=Q.front(); 31 | dequechild; 32 | Q.popf(); 33 | while(!front.empty()){ 34 | TreeNode *each=front.front(); 35 | front.popf(); 36 | 37 | if(each->left!=NULL){ 38 | child.pushb(each->left); 39 | } 40 | if(each->right!=NULL){ 41 | child.pushb(each->right); 42 | } 43 | 44 | } 45 | 46 | if(!child.empty()){ 47 | Q.pushb(child); 48 | vi insertChild; 49 | for(auto ele:child){ 50 | insertChild.pushb(ele->val); 51 | } 52 | soltn.pushb(insertChild); 53 | } 54 | 55 | } 56 | 57 | return soltn; 58 | } 59 | 60 | vector> zigzagLevelOrder(TreeNode* root) { 61 | if(root==NULL){ 62 | return {}; 63 | } 64 | vvi soltn=bfs(root); 65 | 66 | int i; 67 | REP(i,1,soltn.size()){ 68 | int j=0; 69 | int k=soltn[i].size()-1; 70 | while(j 2 | using namespace std; 3 | typedef long long ll; 4 | #define vi vector 5 | #define vll vector 6 | #define vvi vector> 7 | #define vvll vector> 8 | #define pushb push_back 9 | #define popf pop_front 10 | #define popb pop_back 11 | #define pushf push_front 12 | #define REP(i,a,b) for(ll i=a;i> 15 | #define sll set 16 | 17 | void inputArray(vvll & arr,ll n){ 18 | while(n--){ 19 | ll s,d;cin>>s>>d; 20 | arr.pushb({s,d}); 21 | } 22 | } 23 | 24 | int checkRange(sll setEle,vll vecEle){ 25 | //cout<<"Checking :"; 26 | //cout<<*setEle.begin()<<" "<>n; 85 | vvll arr; 86 | inputArray(arr,n); 87 | sort(arr.begin(),arr.end()); 88 | vvll soltn=merge(arr); 89 | 90 | for(auto each:soltn){ 91 | for(auto every:each){ 92 | cout<ele: 15 | u=m-1 16 | else: 17 | l=m+1 18 | return [-1] 19 | 20 | if __name__=="__main__": 21 | towers=list(map(int,input().split())) 22 | listeners=list(map(int,input().split())) 23 | 24 | i=0 25 | 26 | 27 | while listeners!=[]: 28 | if i==0: 29 | for each_tower in range(0,len(towers)): 30 | ele=towers[each_tower] 31 | towers[each_tower]=[ele-1,ele+1] 32 | else: 33 | for each_tower in range(0,len(towers)): 34 | ele=towers[each_tower] 35 | if ele[0]-1<0: 36 | ele[0]=0 37 | else: 38 | ele[0]=ele[0]-1 39 | if ele[1]+1>1000: 40 | ele[1]=1000 41 | else: 42 | ele[1]=ele[1]+1 43 | towers[each_tower]=[ele[0],ele[1]] 44 | i=i+1 45 | print("towers array is : ",towers,"and listerners array is :",listeners) 46 | for each_tower in range(0,len(towers)): 47 | ele=towers[each_tower] 48 | 49 | #print("Element is : ",ele) 50 | if binSearch(listeners,ele[0])[0]!=-1: 51 | #print("Searching",ele[0]) 52 | listeners.pop(binSearch(listeners,ele[0])[1]) 53 | #print("First part solved") 54 | if binSearch(listeners,ele[1])[0]!=-1: 55 | #print("Searching",ele[1]) 56 | listeners.pop(binSearch(listeners,ele[1])[1]) 57 | 58 | print(i) 59 | 60 | """ 61 | 10 62 | 2 5 3 63 | towers array is : [[9, 11]] and listerners array is : [2, 5, 3] 64 | towers array is : [[8, 12]] and listerners array is : [2, 5, 3] 65 | towers array is : [[7, 13]] and listerners array is : [2, 5, 3] 66 | towers array is : [[6, 14]] and listerners array is : [2, 5, 3] 67 | towers array is : [[5, 15]] and listerners array is : [2, 5, 3] 68 | towers array is : [[4, 16]] and listerners array is : [2, 3] 69 | towers array is : [[3, 17]] and listerners array is : [2, 3] 70 | towers array is : [[2, 18]] and listerners array is : [2] 71 | 8 72 | """ 73 | 74 | 75 | 76 | 77 | -------------------------------------------------------------------------------- /Dynamic Programming/longestArithematicProgression.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define MAX 1001 4 | void input(vector&arr,int n); 5 | 6 | 7 | 8 | int main(){ 9 | 10 | int t;cin>>t; 11 | while(t--){ 12 | 13 | vectorarr; 14 | int n ;cin>>n; 15 | input(arr,n); 16 | 17 | vector>arrayOfDict; 18 | mapchild; 19 | child[arr[0]]=0; 20 | arrayOfDict.push_back(child); 21 | int soltn=0; 22 | 23 | int index=1; 24 | 25 | for(int i=1;iprevious=arrayOfDict[j]; 32 | int count=0; 33 | if(previous.find(difference)!=previous.end()){ 34 | count=(*previous.find(difference)).second; 35 | } 36 | 37 | count++; 38 | 39 | if(j==0){ 40 | mapinner; 41 | inner[difference]=count; 42 | arrayOfDict.push_back(inner); 43 | } 44 | else{ 45 | mapalreadyPresent=arrayOfDict.back(); 46 | //alreadyPresent[difference]=count; 47 | arrayOfDict[i][difference]=count; 48 | } 49 | 50 | } 51 | else{ 52 | // element not found in previous index 53 | 54 | if(j==0){ 55 | mapinner; 56 | inner[difference]=1; 57 | arrayOfDict.push_back(inner); 58 | } 59 | else{ 60 | mapalreadyPresent=arrayOfDict.back(); 61 | arrayOfDict[i][difference]=1; 62 | 63 | } 64 | 65 | 66 | 67 | } 68 | } 69 | } 70 | 71 | int max=INT_MIN; 72 | for(auto each:arrayOfDict){ 73 | 74 | for(auto every:each){ 75 | if(max&arr,int n){ 92 | while(n--){ 93 | int ele;cin>>ele; 94 | arr.push_back(ele); 95 | } 96 | } -------------------------------------------------------------------------------- /Fenwick Trees/range-sum-query-mutable.cpp: -------------------------------------------------------------------------------- 1 | #define MAX 30000+1 2 | #define vi vector 3 | #define REP(i,a,b) for(int i=a;i0){ 58 | sum+=fenTree[fenIndex]; 59 | 60 | int twoComplement=get2sComplement(fenIndex); 61 | int andIndex=fenIndex&twoComplement; 62 | fenIndex-=andIndex; 63 | 64 | } 65 | 66 | return sum; 67 | 68 | } 69 | 70 | 71 | NumArray(vector& nums) { 72 | int size=nums.size(); 73 | fenSize=size; 74 | 75 | int index=0; 76 | for(auto ele:nums){ 77 | initUpdate(index,ele); 78 | index++; 79 | } 80 | 81 | arr=nums; 82 | 83 | } 84 | 85 | void update(int i, int val) { 86 | 87 | int initial=arr[i]; 88 | int diff=val-initial; 89 | arr[i]=val; 90 | initUpdate(i,diff); 91 | 92 | } 93 | 94 | int sumRange(int i, int j) { 95 | int iSum=getSum(i-1); 96 | int jSum=getSum(j); 97 | return jSum-iSum; 98 | 99 | } 100 | }; 101 | 102 | /** 103 | * Your NumArray object will be instantiated and called as such: 104 | * NumArray* obj = new NumArray(nums); 105 | * obj->update(i,val); 106 | * int param_2 = obj->sumRange(i,j); 107 | */ -------------------------------------------------------------------------------- /SentenceEquality.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | using namespace std; 9 | 10 | std::vector >pairs; 11 | std::vector >sentences; 12 | 13 | void inputPairs(); 14 | void printPairs(); 15 | void inputSentences(); 16 | void splitSentences(string); 17 | void printSentences(); 18 | 19 | 20 | 21 | 22 | int main(){ 23 | inputPairs(); 24 | printPairs(); 25 | inputSentences(); 26 | printSentences(); 27 | 28 | 29 | 30 | return 0; 31 | } 32 | 33 | 34 | void inputPairs(){ 35 | int n ; std::cout<<"Enter number of pairs of similar words : "; std::cin>>n; 36 | 37 | while(n!=0){ 38 | string s1,s2;std::cin>>s1>>s2; 39 | pairchild; 40 | child.first=s1; 41 | child.second=s2; 42 | pairs.push_back(child); 43 | n--; 44 | } 45 | 46 | } 47 | 48 | void printPairs(){ 49 | std::cout<<"\nPairs are :"< >::iterator i =pairs.begin();i!=pairs.end();i++){ 51 | std::cout<< (*i).first << "\t" << (*i).second <<"\n"; 52 | } 53 | } 54 | 55 | void splitSentences(string s){ 56 | vectorchild; 57 | 58 | for(int i=0;i > ::iterator i=sentences.begin();i!=sentences.end();i++){ 92 | vectorchild=*i; 93 | std::cout<<"Sentences : "<::iterator j=child.begin();j!=child.end();j++){ 96 | std::cout<<*j<<"\t"; 97 | 98 | } 99 | count++; 100 | std::cout< 2 | using namespace std; 3 | typedef long long int ll; 4 | #define REP(i, a, b) for (ll i = a; i < b; i++) 5 | #define vll vector 6 | #define fastIO \ 7 | ios_base::sync_with_stdio(false); \ 8 | cin.tie(NULL); 9 | 10 | vll fentree; 11 | 12 | void printFentree(vll arr) 13 | { 14 | cout << "Fentree is :"; 15 | for (auto ele : arr) 16 | { 17 | cout << ele << " "; 18 | } 19 | cout << endl; 20 | } 21 | 22 | ll getTwoComplement(ll ele) 23 | { 24 | return ele & (-1 * ele); 25 | } 26 | 27 | ll getNext(ll index) 28 | { 29 | ll twoComplement = getTwoComplement(index); 30 | ll andIndex = index & twoComplement; 31 | return index + andIndex; 32 | } 33 | 34 | ll getParent(ll index) 35 | { 36 | ll twoComplement = getTwoComplement(index); 37 | ll andIndex = index & twoComplement; 38 | return index - andIndex; 39 | } 40 | 41 | ll getSum(ll index) 42 | { 43 | 44 | ll fentreeIndex = index + 1; 45 | ll sum = 0; 46 | 47 | while (fentreeIndex > 0) 48 | { 49 | sum += fentree[fentreeIndex]; 50 | fentreeIndex = getParent(fentreeIndex); 51 | } 52 | 53 | return sum; 54 | } 55 | 56 | void initFenTree(ll n, ll ele, ll index) 57 | { 58 | 59 | ll fentreeIndex = index + 1; 60 | 61 | while (fentreeIndex < n + 1) 62 | { 63 | fentree[fentreeIndex] += ele; 64 | 65 | fentreeIndex = getNext(fentreeIndex); 66 | } 67 | } 68 | 69 | int main() 70 | { 71 | fastIO 72 | 73 | ll n; 74 | cin >> n; 75 | 76 | ll i; 77 | vll arr; 78 | 79 | REP(i, 0, n) 80 | { 81 | ll ele; 82 | cin >> ele; 83 | arr.push_back(ele); 84 | fentree.push_back(0); 85 | } 86 | 87 | REP(i, 0, n) 88 | { 89 | initFenTree(n, arr[i], i); 90 | //printFentree(fentree); 91 | } 92 | 93 | ll q; 94 | cin >> q; 95 | 96 | while (q--) 97 | { 98 | 99 | char op; 100 | cin >> op; 101 | 102 | if (op == 'q') 103 | { 104 | 105 | ll l, r; 106 | cin >> l >> r; 107 | l--; 108 | r--; 109 | 110 | ll rSum = getSum(r); 111 | ll lSum = getSum(l - 1); 112 | 113 | cout << rSum - lSum << endl; 114 | } 115 | else 116 | { 117 | 118 | ll i, x; 119 | cin >> i >> x; 120 | i--; 121 | initFenTree(n, x, i); 122 | } 123 | } 124 | 125 | return 0; 126 | } -------------------------------------------------------------------------------- /Tree Algorithms/readme.md: -------------------------------------------------------------------------------- 1 | 2 |
Trees that 💯% 🥇 the race
3 |
4 | BINARY TREE RIGHT SIDE VIEW : 5 | Link to problem 6 |
7 | Intution: 8 |
    9 |
  1. Think of a O(n) solution.
  2. 10 |
  3. Try to traverse the tree.
  4. 11 |
  5. Which traversal are you thinking of DFS or BFS ?
  6. 12 |
13 |
14 | MAX LEVEL SUM OF BINARY TREE : 15 | Link to problem 16 |
17 | Intution: 18 |
    19 |
  1. Think of Tree Traversal Techniques,
  2. 20 |
  3. Okay So now which travels boggles into your mind first?
  4. 21 |
  5. How will you try to maintain the pointer to each level ordered node in your traversal technique? Try to figure out !!
  6. 22 |
23 |
24 | MIN/MAX DEPTH OF BINARY TREE : 25 | Min depth of bin tree   26 | Max depth of bin tree 27 | 28 |
29 | Intution: 30 |
    31 |
  1. Think of Tree Traversal Techniques.
  2. 32 |
  3. Okay So now which travels boggles into your mind first?
  4. 33 |
  5. How will you try to maintain the pointer to each level ordered node in your traversal technique? Try to figure out !!
  6. 34 |
  7. Also try to store the level number per level per element like in a pair(Element,levelNo)
  8. 35 |
  9. For the leaf node compare the maxii and mini values and return the result.
  10. 36 |
37 |
38 | INSERT INTO A BST : 39 | LINK TO PROBLEM   40 | 41 |
42 | Intution: 43 |
    44 |
  1. Think of Tree Traversal Techniques.
  2. 45 |
  3. If inserting element is greater than the current node move to right!!
  4. 46 |
  5. Other wise move to left
  6. 47 |
  7. Check out if root is NULL and return the root node!
  8. 48 |
49 | 50 |
51 | BINARY TREE ZIGZAG LEVEL ORDER TRAVERSAL : 52 | LINK TO PROBLEM   53 | 54 |
55 | Intution: 56 |
    57 |
  1. Think of Tree Traversal Techniques.
  2. 58 |
  3. Make sure to reverse/zig-zag using some approach like even/odd indexing in the choosen traversal techniques.
  4. 59 |
  5. Check out if root is NULL and return appropriate result!
  6. 60 |
61 | -------------------------------------------------------------------------------- /linkedList/readme.md: -------------------------------------------------------------------------------- 1 | 2 |
Linked List that 😨 up your interview !! But they are amazing!!
3 |
4 | DELETE A NODE WITHOUT HEADER!! : 5 | Link to problem 6 |
7 | This at first sight seems to be vague but this problem has a fine Intution inside !!
8 | Intution: 9 |
    10 |
  1. Think of a O(n) solution.
  2. 11 |
  3. Try to play with data by copying the next node data to current one.
  4. 12 |
  5. End up deleting the end node of list.
  6. 13 |
  7. Corner case: What about a single node ?
  8. 14 |
15 |
16 | Swap Nodes in Pairs : 17 | Link to problem 18 |
This of solving it in single traversal without any additional Space !!
19 | Intution: 20 |
    21 |
  1. Think of a O(n) solution.
  2. 22 |
  3. Try to think to work with list containing both even and odd number of nodes!!
  4. 23 |
  5. Corner case: What about a single node or list with no node ?
  6. 24 |
    25 |     Algorithm:
    26 |         def swapPairs(ListNode *head):
    27 |             if(head==NULL):
    28 |                 return NULL
    29 |             if(head->next==NULL):
    30 |                 return head
    31 |             #make ListNode variables:  i,j,t,preI
    32 |             i=head ;  j=head->next ;  head=j;
    33 |             while(i->next!=NULL){
    34 |                 t=j->next;
    35 |                 j->next=i;
    36 |                 i->next=t;
    37 |                 preI=i;
    38 |                 i=i->next;
    39 |                 if(i!=NULL){
    40 |                     j=i->next;
    41 |                     preI->next=j;
    42 |                 }
    43 |                 else{
    44 |                     preI->next=i;
    45 |                     break;
    46 |                 }
    47 |             }
    48 |             //for odd number of nodes in List:
    49 |             if(j==NULL):
    50 |                 preI->next=i;
    51 |             return head;
    52 |     
    53 |
  7. Note: Please try to implement the Algorithm code and visualize the steps then work on implementation part!!
  8. 54 |
55 | 56 |
57 | Merge K Sorted Lists 👍 58 | Link to problem 59 |
60 | This at first sight seems to be tricky but this problem has a fine Intution inside !!
61 | Intution: 62 |
    63 |
  1. Think of a O(nlogn) solution.
  2. 64 |
  3. Try to design or implement a Data Structure that stores the ingested in each of the list a sorted manner . (Hint : related to type of Queues)
  4. 65 |
  5. End up deleting the element from the designed data structure and add it to the generated Linked List .
  6. 66 |
  7. Return head of generated Linked List
  8. 67 |
68 |
69 | -------------------------------------------------------------------------------- /Dynamic Programming/coinChange2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | #define sci(ele) scanf("%d",&ele) 7 | #define scf(ele) scanf("%f",&ele) 8 | #define scd(ele) scanf("%d",&ele) 9 | #define scll(ele) scanf("%lld",&ele) 10 | #define scull(ele) scanf("%ull",&ele) 11 | 12 | #define REP(i,a,b) for(ll i=a;i=b;i--) 14 | 15 | #define pushb push_back 16 | #define pushf push_front 17 | #define popb pop_back 18 | #define popf pop_front 19 | #define ins insert 20 | #define mp make_pair 21 | #define MAX pow(10,6)+1 22 | #define MOD pow(10,9)+7 23 | #define fastio ios_base::sync_with_stdio(false);cin.tie(NULL); 24 | #define googleOp(TestCase,String) cout<<"Case #"<&arr,ll); 31 | ll euclidGCD(ll,ll); 32 | ll factorialDP(ll); 33 | ll powerDnC(ll,ll); 34 | 35 | ll getWays(vectorcoins,int amount){ 36 | vector>table; 37 | vectorchild; 38 | ll i; 39 | 40 | REP(i,0,amount+1){ 41 | if(i==0)child.pushb(1); 42 | else 43 | child.pushb(0); 44 | } 45 | 46 | table.pushb(child); 47 | 48 | i=1; 49 | for(auto ele:coins){ 50 | ll price=ele; 51 | //cout<j)child.pushb(table[i-1][j]); 57 | else child.pushb(table[i-1][j]+child[j-price]); 58 | } 59 | table.pushb(child); 60 | i++; 61 | /*cout<<"Ways: "; 62 | for(auto each:child){ 63 | cout<>amount; 78 | int size;cin>>size; 79 | vectorcoins; 80 | inputArray(coins,size); 81 | getWays(coins,amount); 82 | cout<&arr,ll n){ 87 | while(n--){ 88 | ll ele;cin>>ele; 89 | arr.pushb(ele); 90 | } 91 | } 92 | 93 | 94 | ll euclidGCD(ll a,ll b){ 95 | while(a!=b){ 96 | if(a>b)a=a-b; 97 | else b=b-a; 98 | } 99 | return a; 100 | } 101 | 102 | ll factorialDP(ll n){ 103 | vectorfact={1}; 104 | ll i; 105 | ll j=1; 106 | REP(i,1,n+1){ 107 | fact.pushb(fact.back()*j); 108 | j++; 109 | 110 | } 111 | return fact.back(); 112 | } 113 | 114 | ll powerDnC(ll x,ll y){ 115 | if(y==0)return 1; 116 | if(y%2!=0){ 117 | return x*powerDnC(x,y/2)*powerDnC(x,y/2); 118 | } 119 | else{ 120 | return powerDnC(x,y/2)*powerDnC(x,y/2); 121 | } 122 | 123 | } 124 | -------------------------------------------------------------------------------- /Design Problems/circularQueue.c: -------------------------------------------------------------------------------- 1 | #define MAX 1000 2 | #define pri(ele) printf("%d\n",ele); 3 | //#define REP(i,a,b,size) for(int i=a;i!=b;i=(i+1)%size) 4 | 5 | typedef struct { 6 | int arr[MAX]; 7 | int front; 8 | int rear; 9 | int count; 10 | int size; 11 | 12 | } MyCircularQueue; 13 | 14 | /** Initialize your data structure here. Set the size of the queue to be k. */ 15 | 16 | MyCircularQueue* myCircularQueueCreate(int k) { 17 | MyCircularQueue * p=(MyCircularQueue *)malloc(sizeof(MyCircularQueue)); 18 | p->size=k; 19 | p->count=0; 20 | p->front=0; 21 | p->rear=-1; 22 | return p; 23 | } 24 | 25 | /** Insert an element into the circular queue. Return true if the operation is successful. */ 26 | bool myCircularQueueEnQueue(MyCircularQueue* p, int value) { 27 | if(p->count==p->size)return false; 28 | p->count++; 29 | if(p->rear==-1){ 30 | p->rear++; 31 | p->arr[p->rear]=value; 32 | pri(p->arr[p->rear]); 33 | //cout<arr[p->rear]<<"\n"; 34 | return true; 35 | } 36 | p->rear=(p->rear+1)%p->size; 37 | p->arr[p->rear]=value; 38 | pri(p->arr[p->rear]); 39 | return true; 40 | 41 | } 42 | 43 | /** Delete an element from the circular queue. Return true if the operation is successful. */ 44 | bool myCircularQueueDeQueue(MyCircularQueue* p) { 45 | if(p->count==0)return false; 46 | p->count--; 47 | p->front=(p->front+1)%p->size; 48 | return true; 49 | } 50 | 51 | /** Get the front item from the queue. */ 52 | int myCircularQueueFront(MyCircularQueue* p) { 53 | if(p->count==0)return -1; 54 | return p->arr[p->front]; 55 | } 56 | 57 | /** Get the last item from the queue. */ 58 | int myCircularQueueRear(MyCircularQueue* p) { 59 | /*int i; 60 | 61 | REP(i,p->front,p->rear+1,p->size){ 62 | pri(p->arr[i]); 63 | }*/ 64 | 65 | if(p->count==0)return -1; 66 | return p->arr[p->rear]; 67 | } 68 | 69 | /** Checks whether the circular queue is empty or not. */ 70 | bool myCircularQueueIsEmpty(MyCircularQueue* p) { 71 | if(p->count==0)return true; 72 | return false; 73 | 74 | } 75 | 76 | /** Checks whether the circular queue is full or not. */ 77 | bool myCircularQueueIsFull(MyCircularQueue* p) { 78 | if(p->count==p->size)return true; 79 | return false; 80 | } 81 | 82 | void myCircularQueueFree(MyCircularQueue* obj) { 83 | free(obj); 84 | } 85 | 86 | /** 87 | * Your MyCircularQueue struct will be instantiated and called as such: 88 | * MyCircularQueue* obj = myCircularQueueCreate(k); 89 | * bool param_1 = myCircularQueueEnQueue(obj, value); 90 | 91 | * bool param_2 = myCircularQueueDeQueue(obj); 92 | 93 | * int param_3 = myCircularQueueFront(obj); 94 | 95 | * int param_4 = myCircularQueueRear(obj); 96 | 97 | * bool param_5 = myCircularQueueIsEmpty(obj); 98 | 99 | * bool param_6 = myCircularQueueIsFull(obj); 100 | 101 | * myCircularQueueFree(obj); 102 | */ -------------------------------------------------------------------------------- /List Shuffling/List Shuffling.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | typedef struct node{ 7 | long long int val; 8 | struct node *next; 9 | }node; 10 | 11 | typedef struct head{ 12 | node *start; 13 | node *tail; 14 | }head; 15 | 16 | void createList(head *,long long int); // This function is to create Linked List initially in O(1). 17 | void printList(head *); // This function is to print List in O(n). 18 | node * findMiddle(head *); // This returns the pointer to node which lies exactly in Middle . O(n/2) => O(n). 19 | node * shuffle(head * ,head *); // This is Shuffling which returns new header of Linked List in O(n). 20 | 21 | 22 | int main(){ 23 | std::cout<<"Enter number of Elements in Linked List : "; 24 | int n; std::cin>>n; 25 | head x; 26 | x.start=NULL; 27 | x.tail=NULL; 28 | 29 | while(n!=0){ 30 | std::cout<<"\nEnter data : "; long long int ele;std::cin>>ele; 31 | createList(&x,ele); 32 | std::cout<next; 40 | middle->next=NULL; 41 | head h2; h2.start=x.start; 42 | 43 | std::cout<<"\nFirst List obtained :"<next=NULL; 57 | newNode->val=ele; 58 | if(t->start==NULL){ 59 | t->start=newNode; 60 | t->tail=newNode; 61 | return ; 62 | } 63 | t->tail->next=newNode; 64 | t->tail=newNode; 65 | } 66 | 67 | void printList(head *t){ 68 | node *p; 69 | p=t->start; 70 | if(t->start==NULL){ 71 | std::cout<<"List Empty"<val<<"\t"; 77 | p=p->next; 78 | } 79 | 80 | } 81 | 82 | node * findMiddle(head *t){ 83 | node *slow=t->start; 84 | node *fast=t->start; 85 | 86 | while(fast->next!=NULL && fast->next->next!=NULL){ 87 | fast=fast->next->next; 88 | slow=slow->next; 89 | } 90 | std::cout<<"\nMiddle element: "<val<start; 96 | node *q=t2->start; 97 | 98 | node * temp1=p->next; 99 | node * temp2=q->next; 100 | 101 | while(temp1!=NULL){ 102 | p->next=q; 103 | q->next=temp1; 104 | p=temp1; 105 | temp1=temp1->next; 106 | q=temp2; 107 | temp2=temp2->next; 108 | 109 | } 110 | 111 | p->next=q; 112 | 113 | return t1->start; 114 | 115 | 116 | } -------------------------------------------------------------------------------- /Design Problems/implement-trie-prefix-tree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define vN vector 4 | #define instruct() cout<<"ENTER 1)INSERT 2)SEARCH 3)STARTS-WITH 4)Exit"; 5 | #define REP(i,a,b) for(int i=a;inext[ele-'a']==NULL){ 37 | 38 | trieNode *newNode =new trieNode ; 39 | 40 | newNode->endOfWord=false; 41 | 42 | if(index==size-1) 43 | newNode->endOfWord=true; 44 | 45 | p->next[ele-'a']=newNode; 46 | 47 | p=p->next[ele-'a']; 48 | 49 | 50 | 51 | } 52 | else{ 53 | if(index==size-1) 54 | p->next[ele-'a']->endOfWord=true; 55 | 56 | p=p->next[ele-'a']; 57 | 58 | } 59 | index++; 60 | 61 | } 62 | 63 | } 64 | 65 | /** Inserts a word into the trie. */ 66 | void insert(string word) { 67 | insertWord(&x,word); 68 | } 69 | 70 | bool searchWord(trieNode *root,string word){ 71 | 72 | trieNode *p=root; 73 | 74 | for(auto ele:word){ 75 | 76 | if(p->next[ele-'a']!=NULL){ 77 | p=p->next[ele-'a']; 78 | } 79 | else{ 80 | return false; 81 | } 82 | 83 | 84 | } 85 | return p->endOfWord; 86 | 87 | 88 | } 89 | 90 | /** Returns if the word is in the trie. */ 91 | bool search(string word) { 92 | return searchWord(&x,word); 93 | } 94 | 95 | 96 | bool startWithWord(trieNode *root,string word){ 97 | trieNode *p=root; 98 | 99 | for(auto ele:word){ 100 | if(p->next[ele-'a']==NULL){ 101 | return false; 102 | } 103 | p=p->next[ele-'a']; 104 | 105 | 106 | } 107 | return true; 108 | 109 | } 110 | 111 | /** Returns if there is any word in the trie that starts with the given prefix. */ 112 | bool startsWith(string prefix) { 113 | 114 | return startWithWord(&x,prefix); 115 | } 116 | }; 117 | 118 | /** 119 | * Your Trie object will be instantiated and called as such: 120 | * Trie* obj = new Trie(); 121 | * obj->insert(word); 122 | * bool param_2 = obj->search(word); 123 | * bool param_3 = obj->startsWith(prefix); 124 | */ 125 | -------------------------------------------------------------------------------- /numberofIslands.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define pushb push_back 3 | #define popf pop_front 4 | #define MAX 200 5 | using namespace std; 6 | int matrix[MAX][MAX]={0}; 7 | int visited[MAX][MAX]={0}; 8 | 9 | 10 | void printTable(int r,int c){ 11 | for(int i=0;i<=r;i++){ 12 | for(int j=0;j<=r;j++){ 13 | 14 | cout<>ele; 26 | matrix[i][j]=ele; 27 | } 28 | } 29 | // printTable(r,c); 30 | } 31 | 32 | 33 | 34 | void printDeque(deque >arr){ 35 | for(deque >::iterator i=arr.begin();i!=arr.end();i++){ 36 | cout<<"("<<(*i).first<<","<<(*i).second<<")"<<",\t"; 37 | } 38 | cout< >pairs; 52 | 53 | if(pairs.size()==0) 54 | count++; 55 | 56 | 57 | pairs.pushb({i,j}); 58 | visited[i][j]=1; 59 | 60 | while(!pairs.empty()){ 61 | int x=pairs.front().first; 62 | int y=pairs.front().second; 63 | 64 | //cout<<"\nDEQUEUE OBTAINED :"<>r>>c; 115 | input(r,c); 116 | getMaxConnection(r,c); 117 | 118 | 119 | return 0; 120 | } 121 | -------------------------------------------------------------------------------- /Dynamic Programming/shortestCommonSupersequence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define MAX 1001 4 | #define REP(i,a,b) for(int i=a;iLCS; 27 | 28 | while(i>=1 && j>=1){ 29 | 30 | if(x[i-1]==y[j-1]){ 31 | LCS.push(x[i-1]); 32 | i--; 33 | j--; 34 | } 35 | else{ 36 | if(table[i-1][j]>table[i][j-1]){ 37 | i--; 38 | } 39 | else{ 40 | j--; 41 | } 42 | } 43 | 44 | } 45 | 46 | string soltn=""; 47 | 48 | while(!LCS.empty()){ 49 | soltn+=LCS.top(); 50 | LCS.pop(); 51 | } 52 | 53 | return soltn; 54 | //cout<<"LCS is : "<>a>>b; 90 | fflush(stdin); 91 | fflush(stdout); 92 | 93 | string lcs=fillTable(a,b); 94 | 95 | //cin>>a>>b>>lcs; 96 | getShortestCommonSupersequence(a,b,lcs); 97 | return 0; 98 | } 99 | 100 | void getShortestCommonSupersequence(string a,string b,string lcs){ 101 | int i=0,j=0,l=0; 102 | int lcsSize=lcs.size(); 103 | string ans=""; 104 | 105 | while(l 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | std::map >relations; 10 | std::mapindegree; 11 | std::mapoutdegree; 12 | 13 | int N=0; 14 | 15 | void read(int); 16 | void write(); 17 | void printVector(vector); 18 | void getDegree(); 19 | void inDegree(vector); 20 | void printDegree(string, map); 21 | void getSolution(int); 22 | 23 | 24 | 25 | int main(){ 26 | int n; std::cout<<"Enter number of relations : "; std::cin>>n; 27 | read(n); 28 | write(); 29 | getDegree(); 30 | 31 | printDegree("indegree",indegree); 32 | printDegree("outdegree",outdegree); 33 | 34 | getSolution(n); 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | return 0; 43 | } 44 | 45 | 46 | void read(int n){ 47 | 48 | while(n!=0){ 49 | std::vectorchild; 50 | 51 | string src,des; std::cin>>src>>des; 52 | child.push_back(des); 53 | if(relations.find(src)==relations.end()){ 54 | relations.insert({src,child}); 55 | } 56 | else{ 57 | relations[src].push_back(des);//printVector(relations[src]); 58 | } 59 | 60 | indegree.insert({src,0}); 61 | outdegree.insert({src,0}); 62 | indegree.insert({des,0}); 63 | outdegree.insert({des,0}); 64 | n--; 65 | } 66 | 67 | 68 | } 69 | 70 | void write(){ 71 | std::cout<<"\n"<<"Key" << "\t" << "Value"<<"\n"; 72 | map >::iterator i; 73 | 74 | i=relations.begin(); 75 | while (i!=relations.end()) 76 | { std::cout<first<<"\t"; 77 | printVector(i->second); 78 | 79 | i++; 80 | } 81 | } 82 | 83 | void printVector(vectorarr){ 84 | for(vector::iterator i=arr.begin();i >::iterator i=relations.begin();i!=relations.end();i++){ 94 | outdegree[i->first]=outdegree[i->first]+i->second.size(); 95 | // std::cout<<"yaha hu "<first; 96 | //printVector(i->second); 97 | inDegree(i->second); 98 | 99 | } 100 | 101 | } 102 | 103 | void inDegree(vectorarr){ 104 | for(vector::iterator i=arr.begin();idict){ 111 | std::cout<< type+" map is : \n"; 112 | for(map::iterator i=dict.begin();i!=dict.end();i++) 113 | { 114 | std::cout<first << "\t" << i->second<<"\n"; 115 | } 116 | } 117 | 118 | void getSolution(int n){ 119 | string ans=""; 120 | 121 | for(map::iterator i=indegree.begin();i!=indegree.end();i++){ 122 | if(indegree[i->first]==indegree.size()-1 && outdegree[i->first]==0) 123 | { 124 | ans=i->first;break; 125 | 126 | } 127 | } 128 | if(ans=="")ans="No Celebrity"; 129 | else ans="Celebrity is : "+ans; 130 | std::cout<size=k; 18 | p->front=0; 19 | p->count=0; 20 | p->rear=-1; 21 | return p; 22 | } 23 | 24 | /** Adds an item at the front of Deque. Return true if the operation is successful. */ 25 | 26 | /** Adds an item at the rear of Deque. Return true if the operation is successful. */ 27 | bool myCircularDequeInsertLast(MyCircularDeque* p, int value) { 28 | 29 | if(p->size==p->count)return false; 30 | p->count++; 31 | if(p->count==0){ 32 | p->rear=(p->rear+1)%p->size; 33 | p->arr[p->rear]=value; 34 | return true; 35 | } 36 | p->rear=(p->rear+1)%(p->size); 37 | p->arr[p->rear]=value; 38 | return true; 39 | } 40 | 41 | bool myCircularDequeInsertFront(MyCircularDeque* p, int value) { 42 | if(p->count==p->size)return false; 43 | if(p->count==0){ 44 | if(myCircularDequeInsertLast(p,value))return true; 45 | } 46 | p->count++; 47 | 48 | p->front=(p->front-1)%(p->size); 49 | if(p->front<0)p->front=p->size+p->front; 50 | p->arr[p->front]=value; 51 | return true; 52 | 53 | } 54 | 55 | /** Deletes an item from the front of Deque. Return true if the operation is successful. */ 56 | bool myCircularDequeDeleteFront(MyCircularDeque* p) { 57 | 58 | if(p->count==0)return false; 59 | 60 | p->count--; 61 | p->front=(p->front+1)%(p->size); 62 | return true; 63 | } 64 | 65 | /** Deletes an item from the rear of Deque. Return true if the operation is successful. */ 66 | bool myCircularDequeDeleteLast(MyCircularDeque* p) { 67 | 68 | if(p->count==0)return false; 69 | p->count--; 70 | p->rear=(p->rear-1)%p->size; 71 | if(p->rear<0)p->rear=(p->size+p->rear); 72 | return true; 73 | 74 | } 75 | 76 | /** Get the front item from the deque. */ 77 | int myCircularDequeGetFront(MyCircularDeque* p) { 78 | if(p->count==0)return -1; 79 | return p->arr[p->front]; 80 | 81 | } 82 | 83 | /** Get the last item from the deque. */ 84 | int myCircularDequeGetRear(MyCircularDeque* p) { 85 | if(p->count==0)return -1; 86 | return p->arr[p->rear]; 87 | } 88 | 89 | /** Checks whether the circular deque is empty or not. */ 90 | bool myCircularDequeIsEmpty(MyCircularDeque* obj) { 91 | if(obj->count==0)return true; 92 | return false; 93 | } 94 | 95 | /** Checks whether the circular deque is full or not. */ 96 | bool myCircularDequeIsFull(MyCircularDeque* p) { 97 | if(p->count==p->size)return true; 98 | return false; 99 | } 100 | 101 | void myCircularDequeFree(MyCircularDeque* obj) { 102 | free(obj); 103 | } 104 | 105 | /** 106 | * Your MyCircularDeque struct will be instantiated and called as such: 107 | * MyCircularDeque* obj = myCircularDequeCreate(k); 108 | * bool param_1 = myCircularDequeInsertFront(obj, value); 109 | 110 | * bool param_2 = myCircularDequeInsertLast(obj, value); 111 | 112 | * bool param_3 = myCircularDequeDeleteFront(obj); 113 | 114 | * bool param_4 = myCircularDequeDeleteLast(obj); 115 | 116 | * int param_5 = myCircularDequeGetFront(obj); 117 | 118 | * int param_6 = myCircularDequeGetRear(obj); 119 | 120 | * bool param_7 = myCircularDequeIsEmpty(obj); 121 | 122 | * bool param_8 = myCircularDequeIsFull(obj); 123 | 124 | * myCircularDequeFree(obj); 125 | */ -------------------------------------------------------------------------------- /Design Problems/browserHistory.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | #define instruct cout<<"ENTER CHOICES (INTEGERS) : 1)VISIT 2)BACK 3)FORWARD 4)PRINT HISTORY 5)PRINT REVERSE HISTORY 6)EXIT\n"; 6 | 7 | class BrowserHistory{ 8 | 9 | typedef struct Node { 10 | string webpage; 11 | int index; // 1-Based 12 | struct Node *next; 13 | struct Node *prev; 14 | }Node; 15 | 16 | mapdic; 17 | 18 | Node * rear=NULL; 19 | Node * head=NULL; 20 | int maxSize=0; 21 | 22 | public: 23 | 24 | void printHistory(){ 25 | Node * p=head; 26 | 27 | while(p!=NULL){ 28 | cout<<"("<index<<")"<webpage<<" "; 29 | p=p->next; 30 | 31 | } 32 | cout<index<<")"<webpage<<" "; 42 | p=p->prev; 43 | 44 | } 45 | cout<<"\n"; 46 | 47 | } 48 | 49 | BrowserHistory(string homepage) { 50 | if(rear==NULL && head==NULL){ 51 | // Node *node=(Node *)malloc(sizeof(Node)); 52 | Node * node =new Node; 53 | 54 | node->webpage=homepage; 55 | node->prev=NULL; 56 | node->next=NULL; 57 | node->index=1; 58 | rear=node; 59 | head=node; 60 | dic[1]=node; 61 | maxSize++; 62 | } 63 | //printHistory(); 64 | 65 | 66 | } 67 | 68 | void visit(string url) { 69 | 70 | //Node *node=(Node *)malloc(sizeof(Node)); 71 | Node * node =new Node; 72 | 73 | rear->next=node; 74 | node->webpage=url; 75 | node->next=NULL; 76 | node->prev=rear; 77 | node->index=rear->index+1; 78 | rear=node; 79 | dic[node->index]=node; 80 | 81 | if(node->indexindex; 82 | else 83 | maxSize=node->index; 84 | 85 | //printHistory(); 86 | 87 | 88 | } 89 | 90 | string back(int steps) { 91 | if(rear==NULL){ 92 | return ""; 93 | } 94 | if(rear->index-steps<=0){ 95 | rear=dic[1]; 96 | return rear->webpage; 97 | } 98 | int moveTo=rear->index-steps; 99 | 100 | rear=dic[moveTo]; 101 | 102 | return rear->webpage; 103 | 104 | } 105 | 106 | string forward(int steps) { 107 | 108 | if(rear==NULL){ 109 | return ""; 110 | } 111 | //cout<<"MAX SIZE IS :"<index){ 113 | rear=dic[maxSize]; 114 | return rear->webpage; 115 | } 116 | 117 | int moveTo=rear->index+steps; 118 | rear=dic[moveTo]; 119 | return rear->webpage; 120 | 121 | } 122 | 123 | 124 | 125 | }; 126 | 127 | int main(){ 128 | string homepage,website; 129 | int steps; 130 | 131 | cout<<"ENTER HOMEPAGE :";cin>>homepage; 132 | BrowserHistory *obj=new BrowserHistory(homepage); 133 | while(1){ 134 | instruct 135 | int instruction; 136 | cin>>instruction; 137 | 138 | if(instruction==6) break; 139 | 140 | switch(instruction){ 141 | case(1): 142 | cout<<"ENTER WEBSITE TO VISIT: "; 143 | 144 | cin>>website ; 145 | obj->visit(website); 146 | break; 147 | case(2) : 148 | cout<<"ENTER NUMBER OF STEPS TO GO BACK: "; 149 | cin>>steps; 150 | cout<<"Rear shifted to :"<back(steps)<<"\n"; 151 | break; 152 | case(3): 153 | cout<<"ENTER NUMBER OF STEPS TO GO FORWARD: "; 154 | cin>>steps; 155 | cout<<"Rear shifted to :"<forward(steps)<<"\n"; 156 | break; 157 | case(4): 158 | obj->printHistory(); 159 | break; 160 | case(5): 161 | obj->printReverseHistory(); 162 | break; 163 | 164 | default: 165 | cout<<"INVALID CHOICE "; 166 | 167 | } 168 | 169 | 170 | 171 | } 172 | 173 | return 0; 174 | } -------------------------------------------------------------------------------- /spiral_matrix.py: -------------------------------------------------------------------------------- 1 | def checkAll(matrix): 2 | for i in range(0,len(matrix)): 3 | for j in range(0,len(matrix[i])): 4 | if matrix[i][j]!=-1: 5 | return 0 6 | return 1 7 | 8 | def spiral(matrix): 9 | row=0 10 | col=len(matrix[0])-1 11 | 12 | ans=[] 13 | while True: 14 | if checkAll(matrix)==1: 15 | break 16 | 17 | i=row 18 | j=0 19 | 20 | while j<=col: 21 | ans.append(matrix[i][j]) 22 | #print("First: ",i,j) 23 | 24 | #print(ans) 25 | matrix[i][j]=-1 26 | j=j+1 27 | j=j-1 28 | #print(i,j) 29 | if len(matrix)>=len(matrix[0]): 30 | 31 | while i<=col or i=row: 59 | #print("Third: ",i,j) 60 | ans.append(matrix[i][j]) 61 | #print(ans) 62 | matrix[i][j]=-1 63 | j=j-1 64 | 65 | j=j+1 66 | while i>=row: 67 | #print("Fouth",i,j) 68 | ans.append(matrix[i][j]) 69 | #print(ans) 70 | matrix[i][j]=-1 71 | i=i-1 72 | #print(ans) 73 | row=row+1 74 | col=col-1 75 | return ans 76 | 77 | 78 | 79 | if __name__=="__main__": 80 | R,C=map(int,input().split()) 81 | matrix=[] 82 | for i in range(0,R): 83 | matrix.append(list(map(int,input().split()))) 84 | #print(matrix) 85 | 86 | ans=spiral(matrix) 87 | for i in range(0,len(ans)): 88 | if ans[i]!=-1: 89 | print(ans[i],end=" ") 90 | 91 | """ 92 | OUTPUT : 93 | 94 | PS D:\PROJECTS\Interview-Problems> python .\spiral_matrix.py 95 | 4 4 96 | 1 2 3 4 97 | 5 6 7 8 98 | 9 10 11 12 99 | 13 14 15 16 100 | 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 101 | PS D:\PROJECTS\Interview-Problems> python .\spiral_matrix.py 102 | 1 2 3 4 5 103 | 6 7 8 9 10 104 | 11 12 13 14 15 105 | 16 17 18 19 20 106 | 21 22 23 24 25 107 | 1 2 3 4 5 10 15 20 25 24 23 22 21 16 11 6 7 8 9 14 19 18 17 12 13 108 | PS D:\PROJECTS\Interview-Problems> python .\spiral_matrix.py 109 | 6 3 110 | 1 2 3 111 | 4 5 6 112 | 7 8 9 113 | 10 11 12 114 | 13 14 15 115 | 16 17 18 116 | 1 2 3 6 9 12 15 18 17 16 13 10 7 4 5 8 11 14 117 | PS D:\PROJECTS\Interview-Problems> python .\spiral_matrix.py 118 | 5 4 119 | 1 2 3 4 120 | 5 6 7 8 121 | 9 10 11 12 122 | 13 14 15 16 123 | 17 18 19 20 124 | 1 2 3 4 8 12 16 20 19 18 17 13 9 5 6 7 11 15 14 10 125 | PS D:\PROJECTS\Interview-Problems> python .\spiral_matrix.py 126 | 4 5 127 | 1 2 3 4 5 128 | 6 7 8 9 10 129 | 11 12 13 14 15 130 | 16 17 18 19 20 131 | 1 2 3 4 5 10 15 20 19 18 17 16 11 6 7 8 9 14 13 12 132 | 133 | """ -------------------------------------------------------------------------------- /linkedList/lru.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class LRUCache { 5 | public: 6 | 7 | typedef struct node{ 8 | struct node *next; 9 | struct node *prev; 10 | int val; 11 | int key; 12 | }node; 13 | 14 | node *createNode(int key,int val){ 15 | node *newNode=new node; 16 | newNode->next=NULL; 17 | newNode->prev; 18 | newNode->val=val; 19 | newNode->key=key; 20 | return newNode; 21 | } 22 | 23 | node *head; 24 | node *tail; 25 | unordered_mapnodeLookup; 26 | unordered_mapnodeExistLookup; 27 | int SIZE; 28 | int curSize; 29 | 30 | void insertEnd(int key,int val){ 31 | 32 | nodeExistLookup[key]=true; 33 | node *newNode=createNode(key,val); 34 | nodeLookup[key]=newNode; 35 | 36 | if(head==NULL){ 37 | head=newNode; 38 | tail=newNode; 39 | return ; 40 | } 41 | 42 | tail->next=newNode; 43 | newNode->prev=tail; 44 | tail=tail->next; 45 | 46 | } 47 | 48 | 49 | void printList(){ 50 | 51 | node *p=head; 52 | cout<<"List : "; 53 | while(p!=NULL){ 54 | cout<val<<" "; 55 | p=p->next; 56 | } 57 | cout<next=currentNode; 71 | currentNode->prev=tail; 72 | tail=tail->next; 73 | 74 | } 75 | 76 | void deleteNode(node *currentNode){ 77 | 78 | 79 | if(currentNode==head){ 80 | 81 | if(currentNode->next==NULL){ 82 | head=NULL; 83 | tail=NULL; 84 | return ; 85 | } 86 | head=head->next; 87 | currentNode->next=NULL; 88 | return ; 89 | } 90 | 91 | if(currentNode==tail){ 92 | tail=currentNode->prev; 93 | currentNode->prev=NULL; 94 | return ; 95 | } 96 | 97 | node *prevNode=currentNode->prev; 98 | prevNode->next=currentNode->next; 99 | currentNode->next->prev=prevNode; 100 | currentNode->next=NULL; 101 | currentNode->prev=NULL; 102 | 103 | 104 | } 105 | 106 | LRUCache(int capacity) { 107 | SIZE=capacity; 108 | head=NULL; 109 | tail=NULL; 110 | curSize=0; 111 | } 112 | 113 | int get(int key) { 114 | 115 | if(nodeExistLookup[key]){ 116 | 117 | node *currentNode=nodeLookup[key]; 118 | deleteNode(currentNode); 119 | appendEnd(currentNode); 120 | //printList(); 121 | return currentNode->val; 122 | 123 | } 124 | return -1; 125 | 126 | } 127 | 128 | void put(int key, int value) { 129 | if(nodeExistLookup[key]){// update value and delete the node and append it to end 130 | node *currentNode=nodeLookup[key]; 131 | currentNode->val=value; 132 | deleteNode(currentNode); 133 | appendEnd(currentNode); 134 | } 135 | else{// add node to the end of the list 136 | insertEnd(key,value); 137 | curSize++; 138 | } 139 | 140 | if(curSize>SIZE){// remove front from ll 141 | 142 | nodeExistLookup[head->key]=false; 143 | deleteNode(head); 144 | curSize--; 145 | } 146 | //puts("Put :"); 147 | //cout< 6 | using namespace std; 7 | #define REP(i,a,b) for(int i=a;i 9 | #define vvi vector 10 | #define vc vector 11 | #define vvc vector 12 | #define umap unordered_map 13 | 14 | class Solution { 15 | public: 16 | 17 | umap>subMatValues; 18 | vvi grid; 19 | umap>rowValues; 20 | umap>colValues; 21 | deque>emptyCells; 22 | int emptyCellsCount; 23 | 24 | void updateGrid(vvc board){ 25 | 26 | emptyCells={}; 27 | emptyCellsCount=0; 28 | 29 | 30 | grid=vvi(9,vi(9,-1)); 31 | int count=0; 32 | 33 | int i; 34 | REP(i,0,9){ 35 | int j; 36 | REP(j,0,9){ 37 | if(board[i][j]!='.'){ 38 | grid[i][j]=board[i][j]-'0'; 39 | rowValues[i][grid[i][j]]=true; 40 | colValues[j][grid[i][j]]=true; 41 | string subMatIndex=getSubmatIndex(count); 42 | subMatValues[subMatIndex][grid[i][j]]=true; 43 | } 44 | else{ 45 | emptyCellsCount++; 46 | emptyCells.push_back({i,j,count}); 47 | } 48 | count++; 49 | } 50 | } 51 | } 52 | 53 | string getSubmatIndex(int position){ 54 | int row=position/9; 55 | int col=position%9; 56 | int R; 57 | int C; 58 | 59 | if(row>=0&&row<=2)R=0; 60 | else if(row>=3&&row<=5)R=1; 61 | else R=2; 62 | 63 | 64 | if(col>=0&&col<=2)C=0; 65 | else if(col>=3&&col<=5)C=1; 66 | else C=2; 67 | 68 | return to_string(R)+to_string(C); 69 | 70 | } 71 | 72 | void printBoard(vvi board){ 73 | cout<<"Board :\n"; 74 | for(auto ele:board){ 75 | for(auto every:ele){ 76 | cout<>& board) { 130 | updateGrid(board); 131 | reached=false; 132 | index=0; 133 | //printBoard(grid); 134 | //cout< 2 | using namespace std; 3 | #define umap unordered_map 4 | #define vi vector 5 | #define pushb push_back 6 | #define popb pop_back 7 | 8 | class Twitter 9 | { 10 | public: 11 | /** Initialize your data structure here. */ 12 | 13 | // this is to manage relations for post 14 | umap> relations; 15 | 16 | //umap> posts; 17 | umap>> latestFeeds; 18 | 19 | // This is for individual follower list 20 | umap>foll; 21 | 22 | 23 | umap>>feeds; 24 | 25 | // this is to maintain time of user posting news feed! 26 | int time; 27 | 28 | Twitter() 29 | { 30 | // posts = {}; 31 | latestFeeds={}; 32 | 33 | relations = {}; 34 | time = 0; 35 | } 36 | 37 | /** Compose a new tweet. */ 38 | void postTweet(int userId, int tweetId) 39 | { 40 | latestFeeds[userId].push_back({time, userId, tweetId}); 41 | 42 | feeds[userId].push_back({time,userId,tweetId}); 43 | 44 | for (auto ele : relations[userId]) 45 | { 46 | latestFeeds[ele.first].push_back({time, userId, tweetId}); 47 | } 48 | 49 | time++; 50 | } 51 | 52 | /** Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent. */ 53 | vector getNewsFeed(int userId) 54 | { 55 | vector allTweets; 56 | 57 | vector> allFeeds = latestFeeds[userId]; 58 | 59 | sort(allFeeds.begin(),allFeeds.end()); 60 | 61 | 62 | int count = 0; 63 | 64 | for (auto it = allFeeds.rbegin(); it != allFeeds.rend(); it++) 65 | { 66 | 67 | 68 | int topUser = (*it)[1]; 69 | int topTweet = (*it)[2]; 70 | 71 | 72 | 73 | if (count == 10) 74 | break; 75 | 76 | if(topUser==userId||foll[userId][topUser]){ 77 | allTweets.push_back(topTweet); 78 | count++; 79 | 80 | } 81 | 82 | } 83 | 84 | return allTweets; 85 | } 86 | 87 | /** Follower follows a followee. If the operation is invalid, it should be a no-op. */ 88 | void follow(int followerId, int followeeId) 89 | { 90 | if(followerId==followeeId) 91 | return; 92 | try 93 | { 94 | if(relations[followerId].find(followeeId)==relations[followerId].end()){ 95 | 96 | for(auto ele:feeds[followerId]){ 97 | latestFeeds[followeeId].push_back(ele); 98 | } 99 | 100 | 101 | for(auto ele:feeds[followeeId]){ 102 | latestFeeds[followerId].push_back(ele); 103 | } 104 | 105 | } 106 | relations[followerId][followeeId] = true; 107 | relations[followeeId][followerId] = true; 108 | foll[followerId][followeeId]=true; 109 | 110 | } 111 | catch (int x) 112 | { 113 | } 114 | } 115 | 116 | /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */ 117 | void unfollow(int followerId, int followeeId) 118 | { 119 | 120 | if(followerId==followeeId) 121 | return; 122 | 123 | if(relations[followerId].find(followeeId)!=relations[followerId].end()){ 124 | relations[followeeId][followerId] = false; 125 | relations[followerId][followeeId] = false; 126 | foll[followerId][followeeId]=false; 127 | } 128 | 129 | } 130 | }; 131 | -------------------------------------------------------------------------------- /Union Find/accounts-merge.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define umap unordered_map 4 | #define vs vector 5 | #define vvs vector 6 | 7 | #define REP(i, a, b) for (int i = a; i < b; i++) 8 | 9 | 10 | 11 | class Solution 12 | { 13 | 14 | public: 15 | struct emailID; 16 | struct username; 17 | 18 | typedef struct emailID 19 | { 20 | string s; 21 | struct username *next; 22 | 23 | } emailID; 24 | 25 | typedef struct username 26 | { 27 | string s; 28 | set allEmailsLinked; 29 | } username; 30 | 31 | 32 | 33 | vector> accountsMerge(vector> &accounts) 34 | { 35 | 36 | umap parentDic; 37 | umap emailAdd; 38 | umap emailDic; 39 | 40 | for (auto ele : accounts) 41 | { 42 | 43 | string uname = ele[0]; 44 | vs every = ele; 45 | int size = every.size(); 46 | 47 | int i; 48 | set commonUsernames; // this gives all commonUsernames to maintain transitivity 49 | 50 | REP(i, 0, size) 51 | { 52 | if (emailDic[every[i]]) 53 | { 54 | commonUsernames.insert(emailAdd[every[i]]->next); 55 | } 56 | } 57 | 58 | if (!commonUsernames.empty()) 59 | { // there exists more than one users with same emailID may be multiple 60 | auto parentUname = *commonUsernames.begin(); 61 | parentDic[parentUname] = true; 62 | 63 | for (auto it = commonUsernames.begin(); it != commonUsernames.end(); it++) 64 | { 65 | if(it!=commonUsernames.begin()){ 66 | set emailsLinked = (*it)->allEmailsLinked; 67 | parentDic[*it] = false; 68 | 69 | for (auto visitAllEmailsLinked : emailsLinked) 70 | { 71 | visitAllEmailsLinked->next = parentUname; 72 | parentUname->allEmailsLinked.insert(visitAllEmailsLinked); 73 | } 74 | } 75 | } 76 | 77 | REP(i, 1, size) 78 | { 79 | emailID *newEmail = new emailID; 80 | newEmail->next = parentUname; 81 | parentUname->allEmailsLinked.insert(newEmail); 82 | emailAdd[every[i]] = newEmail; 83 | emailDic[every[i]] = true; 84 | newEmail->s = every[i]; 85 | } 86 | } 87 | else 88 | { 89 | username *newUser = new username; 90 | parentDic[newUser] = true; 91 | newUser->s = uname; 92 | newUser->allEmailsLinked = {}; 93 | 94 | REP(i, 1, size) 95 | { 96 | emailID *newEmail = new emailID; 97 | newEmail->next = newUser; 98 | newUser->allEmailsLinked.insert(newEmail); 99 | emailAdd[every[i]] = newEmail; 100 | emailDic[every[i]] = true; 101 | newEmail->s = every[i]; 102 | } 103 | } 104 | } 105 | 106 | vvs res; 107 | 108 | for(auto everyParent:parentDic){ 109 | if(everyParent.second){ 110 | 111 | auto parent=everyParent.first; 112 | 113 | res.push_back({parent->s}); 114 | 115 | setfinalEmails; 116 | 117 | for(auto everyString:parent->allEmailsLinked){ 118 | finalEmails.insert(everyString->s); 119 | 120 | } 121 | 122 | for(auto everyMail:finalEmails){ 123 | res.back().push_back(everyMail); 124 | } 125 | 126 | 127 | } 128 | } 129 | return res; 130 | } 131 | }; -------------------------------------------------------------------------------- /Geometry/CLOPPAIR.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define fastIO \ 3 | ios_base::sync_with_stdio(false); \ 4 | cin.tie(NULL) 5 | using namespace std; 6 | unsigned long long int MOD = 1e9 + 7; 7 | unsigned long long int MAX = 1e5; 8 | #define pi pair 9 | #define vi vector 10 | #define vvi vector 11 | 12 | #define pushb push_back 13 | #define popf pop_front 14 | #define popb pop_back 15 | #define pushf push_front 16 | 17 | #define REP(i, a, b) for (int i = a; i < b; i++) 18 | #define REPI(i, a, b) for (int i = a; i >= b; i--) 19 | 20 | typedef long long ll; 21 | typedef unsigned long long ull; 22 | 23 | void printPoints(vvi arr); 24 | void printMapofAllPoints(); 25 | 26 | #define mdvi map> 27 | 28 | mdvi mapOfAllPoints; 29 | 30 | double distance(int x1, int y1, int x2, int y2) 31 | { 32 | double dist = sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2)); 33 | vector arr; 34 | // cout << "X1,Y1 :" << x1 << " " << y1 << endl; 35 | // cout << "X2,Y2 :" << x2 << " " << y2 << endl; 36 | // cout << "DIST IS :" << dist << endl; 37 | 38 | arr.push_back({x1, y1}); 39 | arr.push_back({x2, y2}); 40 | mapOfAllPoints[dist] = arr; 41 | 42 | return dist; 43 | } 44 | 45 | bool compareY(vi a, vi b) 46 | { 47 | return a[1] > b[1]; 48 | } 49 | 50 | double stripClosest(vvi strip, double d) 51 | { 52 | 53 | double mini = d; 54 | 55 | sort(strip.begin(), strip.end(), compareY); 56 | 57 | int size = strip.size(); 58 | 59 | int i; 60 | REP(i, 0, size) 61 | { 62 | for (int j = i + 1; j < size && abs(strip[i][1] - strip[j][1]) < mini; j++) 63 | { 64 | mini = min(mini, distance(strip[i][0], strip[i][1], strip[j][0], strip[j][1])); 65 | } 66 | } 67 | return mini; 68 | } 69 | 70 | double divideArr(vvi &arr, int l, int h) 71 | { 72 | //cout << "LOW IS :" << l << " HIGH IS :" << h << endl; 73 | if (abs(l - h) <= 3) 74 | { 75 | double mini = INT_MAX; 76 | int i; 77 | REP(i, l, h) 78 | { 79 | int j; 80 | REP(j, i + 1, h) 81 | { 82 | mini = min(mini, distance(arr[i][0], arr[i][1], arr[j][0], arr[j][1])); 83 | } 84 | } 85 | return mini; 86 | } 87 | 88 | int mid = (l + h) / 2; 89 | double dl = divideArr(arr, l, mid); 90 | double dr = divideArr(arr, mid + 1, h); 91 | 92 | //cout << "dl is :" << dl << " dr is :" << dr << endl; 93 | double d = min(dl, dr); 94 | 95 | //cout << "d is :" << d << endl; 96 | 97 | // strip of d is created and find distance across strip d 98 | vvi strip; 99 | 100 | int i; 101 | REP(i, l, h) 102 | { 103 | if (abs(arr[i][0] - arr[mid][0]) < d) 104 | { 105 | strip.push_back({arr[i][0], arr[i][1]}); 106 | } 107 | } 108 | 109 | return min(d, stripClosest(strip, d)); 110 | } 111 | 112 | int main() 113 | { 114 | fastIO; 115 | int n; 116 | cin >> n; 117 | 118 | vvi arr; 119 | 120 | map allPoints; 121 | int index = 0; 122 | while (n--) 123 | { 124 | int x, y; 125 | cin >> x >> y; 126 | arr.push_back({x, y}); 127 | allPoints[{x, y}] = index; 128 | index++; 129 | } 130 | 131 | sort(arr.begin(), arr.end()); 132 | 133 | //printPoints(arr); 134 | 135 | double distance = divideArr(arr, 0, arr.size()); 136 | 137 | vvi points = mapOfAllPoints[distance]; 138 | 139 | int firstIndex = allPoints[points[0]]; 140 | int secondIndex = allPoints[points[1]]; 141 | 142 | cout << min(firstIndex, secondIndex) << " " << max(firstIndex, secondIndex) 143 | << " "; //<< distance << endl; 144 | 145 | printf("%0.06f", distance); 146 | //printMapofAllPoints(); 147 | 148 | return 0; 149 | } 150 | 151 | void printPoints(vvi arr) 152 | { 153 | for (auto ele : arr) 154 | { 155 | cout << ele[0] << " " << ele[1] << endl; 156 | } 157 | } 158 | 159 | void printMapofAllPoints() 160 | { 161 | 162 | for (auto ele : mapOfAllPoints) 163 | { 164 | cout << ele.first << " : "; 165 | for (auto every : ele.second) 166 | { 167 | cout << every[0] << " " << every[1] << " ------ "; 168 | } 169 | cout << endl; 170 | } 171 | } -------------------------------------------------------------------------------- /Dynamic Programming/readme.md: -------------------------------------------------------------------------------- 1 | 2 |
Those who cannot remember the past they are condemned to repeat it.
3 | 4 |
😫 Try Some simple DP PROBLEMS . This makes you feel 😄
5 |
6 | Longest Common Subsequence : Link to problem 7 |
8 | Shortest Common Supersequence : Link to problem 9 |
10 | Intution 🤔 👍 -->
11 |
    12 |
  1. Try Finding out LCS string. 13 |
  2. With the obtained LCS try integrating the non LCS character in such a way that they occur in the same order of their appearance in their desired strings. 14 |
  3. The solution string is union of LCS and non LCS characters in order of their apprearance. 15 |
16 |
17 | Longest Arithematic Progression : Link to problem 18 |
19 | Intution 🤔 👍 💯 -->
20 |
    21 |
  1. Try to figure out O(n*n) Logic with a hint of storing the common difference between each pair of elements when iterated. 22 |
  2. Try to build a Hash Map dynamically from index (1:size of array) in such a way that Hash Map stores the elements of type {key(common difference):value(counter)} which is referenced for each pair from previously iterated index. 23 |
  3. Try to find out the max counter present in the Hash Map . The (max+1) will give you solution . Guess why? 24 |
  4. Pairing elements helps you find the solution reason for adding 1 behind max is the same as one need to count elements that are paired together. 25 |
26 |
27 | Edit Distance : Leetcode or G4G 28 |
Intution:
29 |
30 | 31 |
32 |
33 | Longest Palindromic Subsequence : Leetcode 34 |
Intution:
35 |
    36 |
  1. Similar to LCS.
  2. 37 |
  3. Just need to find LCS of string and reversed string and return length of LCS.
  4. 38 |
39 | 40 |
41 | Max Profit with atmost one Transaction : Leetcode 42 |
Intution:
43 |
    44 |
  1. Look for a stock in which you feel the profit can be maximized. How?
  2. 45 |
  3. Approach 1: Try Brute Force , i.e. , try designing an algorithm which helps you figure out the profit earned with each stock after selling them once they are bought!! Do you feel Brute Force is optimal enough??
  4. 46 |
  5. Approach 2: Can you figure out how to optimize? Hints:
    47 |
      48 |
    1. Work by maximizing the difference between buying and selling.
    2. 49 |
    3. Can you work with finding a Minimum valued stock and iterating with that stock to all other stocks to find out the maximum absolute differece?
    4. 50 |
    5. Can you do the above task simply while iterating the vector/array once?
    6. 51 |
    7. Biggest Hint for above task : try implementing Priority Queue.
    8. 52 |
    53 |
  6. 54 |
55 | 56 |
57 | Max Profit with K Transactions : AlgoExpert.io 58 |
Intution:
59 | 60 |
61 | K-palindrome : G4G 62 |
Intution:
63 | 64 |
65 | Unique Binary Search Trees : G4G or Leetcode 66 |
Intution
67 |
68 | Coin Change 2 : 69 | Leetcode 70 |
Intution
71 |
72 | 73 | ##### Longest Valid Parenthesis : [Leetcode](https://leetcode.com/problems/longest-valid-parentheses/) 74 | 75 | Intution 👍 🤔 : 76 | 77 |
    78 |
  1. Think of a stack implementation for the problem checking a pair of valid parenthesis. 79 |
  2. The best part is trying to visualize and implement the solution to check for a substring. 80 |
  3. Hint : Can you work with Visited Array anyhow?? 81 |
82 | 83 |
84 | 85 | #### Increasing Triplet Subsequence : [Leetcode](https://leetcode.com/problems/increasing-triplet-subsequence/) 86 | 87 | Intution 🤔 : 88 | 89 |
    90 |
  1. Think of first Brute Force Solution? 91 | Hint : O(n^2) Time and O(n) space 92 |
  2. Try to optimize using a oneMin and twoMin representing the element which is Minimum till count is either one or two. 93 |
  3. Can you optimize Brute Force to O(n) Time and O(1) space using the above two variables? 94 |
  4. Hint: Solution will be 'true' once the element in the present index > twoMin 95 |
96 |
97 | 98 | #### Out of Boundary Paths : [Leetcode](https://leetcode.com/problems/out-of-boundary-paths/) 99 | 100 | Intution 🤔 : 101 | 102 |
    103 |
  1. Think of first Brute Force Solution? 104 | Hint : DFS or BFS Solution with all 4 connected vertices moves! O(4n) Time Complexity 105 |
  2. Try to optimize using a dp 3D Matrix. 106 | Hint : State of dp[moves][x][y] Matrix resembles number ways to reach (x,y) in 'moves' 107 |
  3. Look for Corner cases! 108 |

    109 | 110 | 111 |
112 | 113 |
114 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Interview-Problems 2 | ![Linus Torvals](./images/quoteTorvalds.jpg) 3 | *** 4 | Sorted and Rotated Array (Microsoft, https://codezen.codingninjas.in/practice/128432/3796/interview-shuriken-20:-sorted-and-rotated-array ) 5 |
6 | N-th Prefect Number (Microsoft, https://codezen.codingninjas.in/practice/130452/4641/interview-shuriken-21:-n-th-prefect-number) 7 |
8 | Count distinct elements in every window of size k(Accolite, Amazon and Microsoft,https://codezen.codingninjas.in/practice/199644/5201/interview-shuriken-35:-count-distinct-elements-in-every-window-of-size-k) 9 |
10 | Sort Binary Array (Amazon, Zoho, Paytm and MakeMyTrip , https://codezen.codingninjas.in/practice/236720/5537/interview-shuriken-40:-sort-binary-array) 11 |
12 | First negative integer in every window of size k (Amazon,https://codezen.codingninjas.in/practice/194088/5171/interview-shuriken-34:-first-negative-integer-in-every-window-of-size-k) 13 |
14 | Two Elements(Facebook, https://codezen.codingninjas.in/practice/177734/5008/interview-shuriken-30:-two-elements) 15 |
16 | Move Zeroes to End(Amazon, Bloomberg, Paytm, LinkedIn, Samsung and SAP Labs, https://codezen.codingninjas.in/practice/240143/5577/interview-shuriken-41:-move-zeroes-to-end) 17 |
18 | Delete Middle Node (Flipkart and Microsoft.,https://codezen.codingninjas.in/practice/253059/5741/interview-shuriken-43:-delete-middle-node) 19 |
20 | Loop Detector (Amazon, Accolite, Samsung and MAQ Software ,https://codezen.codingninjas.in/practice/255594/5823/interview-shuriken-44:-loop-detector) 21 |
22 | Pair Sum(initial rounds of Google interview, https://codezen.codingninjas.in/practice/100333/2674/interview-shuriken-1:-pair-sum) 23 |
24 | Find the smallest window in a string containing all characters of another string( Amazon, Factset, MakeMyTrip, Codenation, Streamoid Technologies, Google, Visa, 25 | https://codezen.codingninjas.in/practice/209118/5331/interview-shuriken-37:-find-the-smallest-window-in-a-string-containing-all-characters-of-another-string) 26 |
27 | Happy Number (https://codezen.codingninjas.in/practice/265704/5880/interview-shuriken-45:-happy-number) 28 |
29 | Smallest window that contains all distinct characters(Microsoft, Amazon and DailyHunt,https://codezen.codingninjas.in/practice/188409/5167/interview-shuriken-33:-smallest-window-that-contains-all-distinct-characters) 30 |
31 | Is Palindrome(Snapdeal, Microsoft and Amazon, https://codezen.codingninjas.in/practice/267994/5962/interview-shuriken-46:-is-palindrome) 32 |
33 | Dynamic Programming --> Move_to_other_end ( Determine the minimum number of path taken by a pawn to travel from top-leftmost corner to bottom-right most corner in a n*n chessboard . Note : only Left and Bottom transitions allowed by the pawn. ) 34 |
35 | Amdocs Pattern : 36 | First line as n (number of lines) 37 | 38 | 4 39 | 40 | 1 41 | 42 | 3 * 2 43 | 44 | 4 * 5 * 6 45 | 46 | 10 * 9 * 8 * 7 47 |
48 | 328. Odd Even Linked List (https://leetcode.com/problems/odd-even-linked-list/), 49 | odd_even_link_list_o(n).c 50 |
51 | 21. Merge Two Sorted Lists (https://leetcode.com/problems/merge-two-sorted-lists/) 52 |
53 | 186. Reverse Words in String (Microsoft,Amazon,Uber, https://www.leetfree.com/problems/reverse-words-in-a-string-ii.html#) 54 |
55 | 54. SPIRAL MATRIX (Google, https://leetcode.com/problems/spiral-matrix/ ) -- > Given a matrix of R (Rows) and C(Columns) : 56 | 57 | Print the elements of matrix in spiral order : 58 | 59 | Example : 60 | 61 | 3 3 62 | 63 | 1 2 3 64 | 65 | 4 5 6 66 | 67 | 7 8 9 68 | 69 | 1 2 3 6 9 8 7 4 5 70 |
71 | 70. CLIMBING STAIRCASE (Amazon , https://leetcode.com/problems/climbing-stairs/) 72 | 73 | Problem : CONTIGUOUS SUB-ARRAY SUM : (Google) : 74 | Given a contiguous array of size n of non-negative integers , find a contiguous sub-array which adds to give sum S. 75 | Time: O(n) 76 | Example : 77 | array : [1 2 3 7 5] 78 | S : 12 79 | Output : [2, 4] 80 |
81 | Problem : 82 | This problem was asked by Sumo Logic. 83 | 84 | Given an unsorted array, in which all elements are distinct, find a "peak" element in O(log N) time. 85 | 86 | An element is considered a peak if it is greater than both its left and right neighbors. It is guaranteed that the first and last elements are lower than all others. 87 | 88 | Exmaple : 89 | INPUT : 90 | 91 | 15 20 14 16 48 19 50 60 10 20 30 45 60 92 | 93 | OUTPUT : 94 | 95 | YES 96 | 97 | ALL PEAK ELEMENTS ARE : [20, 48, 60] 98 |
99 | Problem : (Google interview) : 100 | Given two arrays A and B and a targetSum to be achieved , write a function that returns "True" or "False" such that : if a number choosen from A and a number choosen from B has a sum equal to targetSum. 101 | 102 | Example: 103 | 104 | Input : 105 | A=> [25 30 41 60 10 -5 60 -2] 106 | B=> [-1 0 20 60] 107 | tragetSum=> -3 108 | Output : 109 | True 110 | 111 |
112 | Problem: (Towers and Listeners) This problem was asked by Spotify. 113 | 114 | You are the technical director of WSPT radio, serving listeners nationwide. For simplicity's sake we can consider each listener to live along a horizontal line stretching from 0 (west) to 1000 (east). 115 | 116 | Given a list of N listeners, and a list of M radio towers, each placed at various locations along this line, determine what the minimum broadcast range would have to be in order for each listener's home to be covered. 117 | 118 | For example, suppose listeners = [1, 5, 11, 20], and towers = [4, 8, 15]. In this case the minimum range would be 5, since that would be required for the tower at position 15 to reach the listener at position 20. 119 |
120 | 34. Find First and Last Position of Element in Sorted Array (Facebook ,https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/) 121 |
122 | *PROBLEM:place_all_x_and_y_together* : This problem was asked by LinkedIn. 123 | 124 | You are given a string consisting of the letters x and y, such as xyxxxyxyy. In addition, you have an operation called flip, which changes a single x to y or vice versa. 125 | 126 | Determine how many times you would need to apply this operation to ensure that all x's come before all y's. In the preceding example, it suffices to flip the second and sixth characters, so you should return 2. 127 |
128 | 129 | This problem was asked by Pinterest. 130 | 131 | At a party, there is a single person who everyone knows, but who does not know anyone in return (the "celebrity"). To help figure out who this is, you have access to an O(1) method called knows(a, b), which returns True if person a knows person b, else False. 132 | 133 | Given a list of N people and the above operation, find a way to identify the celebrity in O(N) time. 134 | 135 | D:\C++ FILES>elexe
136 | Enter number of relations : 6
137 | sid aman
138 | rohan aman
139 | amulya aman
140 | rohan amulya
141 | ankita aman
142 | vinay aman
143 | 144 | Key Value
145 | amulya aman
146 | ankita aman
147 | rohan aman amulya
148 | sid aman
149 | vinay aman
150 | 151 | indegree map is : 152 | aman 5
153 | amulya 1
154 | ankita 0
155 | rohan 0
156 | sid 0
157 | vinay 0
158 | outdegree map is :
159 | aman 0
160 | amulya 1
161 | ankita 1
162 | rohan 2
163 | sid 1
164 | vinay 1
165 | Celebrity is aman 166 |
167 | List Shuffling 168 |
169 | 170 | This problem was asked by Google. 171 | 172 | link : https://leetcode.com/problems/range-sum-of-bst 173 | 174 | Given a binary search tree and a range [a, b] (inclusive), return the sum of the elements of the binary search tree within the range. 175 | 176 | For example, given the following tree: 177 | 178 | 5 179 | 180 | / \ 181 | 182 | 3 8 183 | 184 | / \ / \ 185 | 186 | 2 4 6 10
187 | 188 | and the range [4, 9], return 23 (5 + 4 + 6 + 8). 189 | 190 |
191 | 192 | Interview Shuriken 54: Missing K Natural Numbers 193 | 194 |
195 | 196 | Sentence Equality 197 | 198 | This problem was asked by Google. 199 | 200 | You are given a set of synonyms, such as (big, large) and (eat, consume). Using this set, determine if two sentences with the same number of words are equivalent. 201 | 202 | For example, the following two sentences are equivalent: 203 | 204 | "He wants to eat food." 205 | "He wants to consume food." 206 | Note that the synonyms (a, b) and (a, c) do not necessarily imply (b, c): consider the case of (coach, bus) and (coach, teacher). 207 | 208 | Follow-up: what if we can assume that (a, b) and (a, c) do in fact imply (b, c)? 209 | 210 |
211 | 212 | Interview Shuriken 55: Missing Numbers 213 | 214 |
215 | 216 | This problem asked by : *Amazon* 217 | Interview Shuriken 26: Number of Islands 218 | 219 |
220 | 221 | 222 | This problem asked by : *Google* 223 | Interview Shuriken 17: Sort RGB 224 | 225 |
226 | 227 | This problem asked by : *Amazon* 228 | Interview Shuriken 15: Run Length Encoding 229 | 230 |
231 | 232 | This problem asked by *Google* 233 | Unival Subtrees Leetcode 234 | 235 |
236 | 237 | This problem was asked by Squarespace. 238 | 239 | Write a function, add_subtract, which alternately adds and subtracts curried arguments. Here are some sample operations: 240 | 241 | add_subtract(7) -> 7 242 | 243 | add_subtract(1)(2)(3) -> 1 + 2 - 3 -> 0 244 | 245 | add_subtract(-5)(10)(3)(9) -> -5 + 10 - 3 + 9 -> 11 246 | 247 | Link to code curry.py 248 |
249 | 250 | This problem was asked by *Google* 251 | Valid Parenthesis String 252 | 253 |
254 | 255 | This Code is asked by Google 256 | Link to problem 257 |
258 | Solution 259 | 260 |
261 | This problem was asked by Amazon. 262 | 263 | Write a function that takes a natural number as input and returns the number of digits the input has. 264 | 265 | Constraint: don't use any loops. 266 | 267 |
268 | 269 | 270 | 271 | 272 | --------------------------------------------------------------------------------