├── Codechef ├── Cook-Off │ ├── FEB19 │ │ ├── CHFPARTY.py │ │ └── TABLET.py │ └── MAR19 │ │ └── NBONACCI.py ├── Long_Challenge │ ├── FEB19 │ │ ├── CHEFING.py │ │ └── HMAPPY2.py │ └── MAR19 │ │ └── CHNUM.py └── Lunch_Time │ └── FEB19 │ └── AVG.py ├── Geeks For Geeks ├── BASIC │ ├── Count nodes of linked list.py │ ├── Find second largest element.py │ ├── Find the closest number.py │ ├── Immediate Smaller Element.py │ ├── Multiply left and right array sum.py │ ├── Print an array in Pendulum Arrangement.py │ ├── Product of array elements.py │ ├── Repeated I.Ds.py │ ├── Reverse array in groups.py │ ├── Rotating an Array.py │ ├── Search an Element in an array.py │ ├── Sort in specific order.py │ ├── Space Seperated - Python.py │ ├── Start Coding - Python.py │ └── Transform to prime.py ├── EASY │ ├── Chocolate Distribution Problem.py │ ├── Index Of an Extra Element.py │ ├── Leaders in an array.py │ ├── SP - Palindrome Family.py │ ├── Sort an array of 0s, 1s and 2s.py │ ├── Subarray with given sum.py │ ├── Sum of given range.py │ └── Triangular Number.py ├── HARD │ └── Return two prime numbers.py ├── MEDIUM │ ├── Case-specific Sorting of Strings.py │ ├── Excel Sheet | Part - 1.py │ ├── Find Prime numbers in a range.py │ ├── Kth smallest element.py │ ├── Multiply two strings.py │ ├── Nearly Sorted Algorithm.py │ └── Sum of bit differences.py └── SCHOOL │ ├── Print alternate elements of an array.py │ └── Reverse an Array.py ├── Hacker Blocks └── GENERAL │ └── Rotate Image ├── InterviewBit ├── Day 17 : Two Pointers │ └── Assignment │ │ └── Count of pairs with the given sum ├── Day 2: Array and Math │ └── Assignment │ │ └── Closest MinMax ├── Day 6 │ ├── Assignment │ │ ├── Delete Elements │ │ ├── Delete one │ │ ├── Divisor Game │ │ ├── Greatest Common Divisor │ │ └── Pubg │ └── Homework │ │ ├── A, B and Modulo │ │ ├── Consecutive Number Sum │ │ ├── Enumerating GCD │ │ └── Trailing Zeros in Factorial ├── Day 8 │ ├── Assignment │ │ ├── Count of divisors for multiple queries │ │ └── Factorial Array │ └── Homework │ │ ├── Find nth Magic Number │ │ ├── Lucky Numbers │ │ └── Prime Sum └── Day-3 │ └── HomeWork │ └── Alternate positive and negative elements (Using Extra Space) ├── LeetCode ├── Easy │ ├── Binary Search.md │ ├── Binary Tree Tilt.md │ ├── Buddy Strings.md │ ├── Complement of Base 10 Integer.md │ ├── Consecutive Characters.md │ ├── Convert Binary Number in a Linked List to Integer.md │ ├── Find the Difference.md │ ├── Flipping an Image.md │ ├── Minimum Cost to Move Chips to The Same Position.md │ ├── Minimum Depth of Binary Tree.md │ ├── Number of Recent Calls.md │ └── Summary Ranges.md ├── Hard │ ├── Best Time to Buy and Sell Stock IV.md │ ├── First Missing Positive.md │ ├── Recover Binary Search Tree.md │ ├── Stone Game IV.md │ └── Unique Paths III.md ├── Medium │ ├── 132 Pattern.md │ ├── Add Two Numbers II.md │ ├── Asteroid Collision.md │ ├── Bag of Tokens.md │ ├── Car Pooling.md │ ├── Champagne Tower.md │ ├── Clone Graph.md │ ├── Combination Sum.md │ ├── Evaluate Division.md │ ├── Gas Station.md │ ├── House Robber II.md │ ├── Insert into a Binary Search Tree.md │ ├── Insertion Sort List.md │ ├── K-diff Pairs in an Array.md │ ├── Largest Number.md │ ├── Linked List Cycle II.md │ ├── Majority Element II.md │ ├── Maximize Distance to Closest Person.md │ ├── Maximum Difference Between Node and Ancestor.md │ ├── Minimum Domino Rotations For Equal Row.md │ ├── Minimum Height Trees.md │ ├── Minimum Number of Arrows to Burst Balloons.md │ ├── Number of Longest Increasing Subsequence.md │ ├── Remove Covered Intervals.md │ ├── Remove Duplicate Letters.md │ ├── Repeated DNA Sequences.md │ ├── Rotate Array.md │ ├── Rotate List.md │ ├── Search a 2D Matrix.md │ ├── Sequential Digits.md │ ├── Sort List.md │ ├── Subarray Product Less Than K.md │ ├── Teemo Attacking.md │ └── Word Break.md └── Premium │ ├── 161. One Edit Distance.md │ ├── 253. Meeting Rooms II.md │ ├── 2534. Time Taken to Cross the Door.md │ ├── 266. Palindrome Permutation.md │ ├── 346. Moving Average from Data Stream.md │ ├── 364. Nested List Weight Sum II.md │ ├── 444. Sequence Reconstruction.md │ ├── Missing Ranges.md │ ├── Nested List Weight Sum.md │ ├── Palindrome Permutation.md │ ├── Plus One Linked List.md │ ├── Shortest Word Distance.md │ ├── Valid Word Square.md │ └── Word Squares.md └── README.md /Codechef/Cook-Off/FEB19/CHFPARTY.py: -------------------------------------------------------------------------------- 1 | ## Question : https://www.codechef.com/COOK103B/problems/CHFPARTY/ 2 | 3 | def main(): 4 | testcases = int(input()) 5 | for test in range(testcases): 6 | no_of_friends = int(input()) 7 | friends = list(map(int,input().split())) 8 | people_at_party = 0 9 | friends.sort() 10 | for friend in friends: 11 | if people_at_party >= friend: 12 | people_at_party += 1 13 | else: 14 | break 15 | print(people_at_party) 16 | 17 | if __name__ == "__main__": 18 | main() 19 | -------------------------------------------------------------------------------- /Codechef/Cook-Off/FEB19/TABLET.py: -------------------------------------------------------------------------------- 1 | ## Question link : https://www.codechef.com/COOK103B/problems/TABLET/ 2 | 3 | def main(): 4 | testcases = int(input()) 5 | for _ in range(testcases): 6 | tablets,budget = map(int,input().split()) 7 | max_area = -1 8 | for tablet in range(tablets): 9 | width,height,price = map(int,input().split()) 10 | if price <= budget: 11 | area = width*height 12 | if area > max_area: 13 | max_area = area 14 | if max_area == -1: 15 | print("no tablet") 16 | else: 17 | print(max_area) 18 | 19 | 20 | 21 | if __name__ == "__main__": 22 | main() 23 | -------------------------------------------------------------------------------- /Codechef/Cook-Off/MAR19/NBONACCI.py: -------------------------------------------------------------------------------- 1 | ## Question link : https://www.codechef.com/problems/NBONACCI 2 | 3 | from sys import stdin 4 | def main(): 5 | n,q = map(int,stdin.readline().split()) 6 | arr = list(map(int,stdin.readline().split())) 7 | f = [0,arr[0]] 8 | xor = arr[0]^arr[1] 9 | f.append(xor) 10 | for index in range(2,n): 11 | xor ^= arr[index] 12 | f.append(xor) 13 | for query in range(q): 14 | k = int(stdin.readline()) 15 | if k <= n: 16 | print(f[k]) 17 | else: 18 | print(f[k%(n+1)]) 19 | 20 | if __name__ == "__main__": 21 | main() 22 | 23 | ## Solution link : https://www.codechef.com/viewsolution/23675823 24 | -------------------------------------------------------------------------------- /Codechef/Long_Challenge/FEB19/CHEFING.py: -------------------------------------------------------------------------------- 1 | ## Question link : https://www.codechef.com/FEB19B/problems/CHEFING 2 | ## Solution link : https://www.codechef.com/viewsolution/22716695 3 | 4 | letters_dic = {"a":0,"b":0,"c":0,"d":0,"e":0,"f":0,"g":0,"h":0,"i":0,"j":0,"k":0,"l":0,"m":0,"n":0,"o":0,"p":0,"q":0,"r":0,"s":0,"t":0,"u":0,"v":0,"w":0,"x":0,"y":0,"z":0} 5 | for _ in range(int(input())): 6 | n = int(input()) 7 | letters_dic = letters_dic.fromkeys(letters_dic,0) 8 | ans = [] 9 | for temp in range(n): 10 | s = input() 11 | for i in set(s): 12 | letters_dic[i] += 1 13 | if letters_dic[i] == n: 14 | ans.append(i) 15 | print(len(ans)) 16 | #print(ans) 17 | -------------------------------------------------------------------------------- /Codechef/Long_Challenge/FEB19/HMAPPY2.py: -------------------------------------------------------------------------------- 1 | ## Question link : https://www.codechef.com/FEB19B/problems/HMAPPY2/ 2 | 3 | def gcd(x,y): 4 | while y: 5 | x,y = y,x%y 6 | return x 7 | 8 | def lcm(a,b): 9 | return (a*b) // gcd(a,b) 10 | 11 | for _ in range(int(input())): 12 | n,a,b,k = map(int,input().split()) 13 | count = 0 14 | a_count = n // a 15 | b_count = n // b 16 | ab_count = n // lcm(a,b) 17 | 18 | #print(a_count,b_count,ab_count*2) 19 | 20 | if (a_count + b_count - (ab_count*2)) >= k: 21 | print("Win") 22 | else: 23 | print("Lose") 24 | 25 | # Solution link : https://www.codechef.com/viewsolution/22715987 26 | -------------------------------------------------------------------------------- /Codechef/Long_Challenge/MAR19/CHNUM.py: -------------------------------------------------------------------------------- 1 | ## Question link : https://www.codechef.com/MARCH19B/problems/CHNUM/ 2 | def main(): 3 | testcases = int(input()) 4 | for test in range(testcases): 5 | array_size = int(input()) 6 | scores = list(map(int,input().split())) 7 | positive_numbers = 0 8 | negative_numbers = 0 9 | for score in scores: 10 | if score > 0: 11 | positive_numbers += 1 12 | else: 13 | negative_numbers += 1 14 | if positive_numbers == 0: 15 | print(negative_numbers,negative_numbers) 16 | elif negative_numbers == 0: 17 | print(positive_numbers,positive_numbers) 18 | else: 19 | if positive_numbers > negative_numbers: 20 | print(positive_numbers,negative_numbers) 21 | else: 22 | print(negative_numbers,positive_numbers) 23 | 24 | if __name__ == "__main__": 25 | main() 26 | 27 | ## Solution link : https://www.codechef.com/viewsolution/23316803 28 | -------------------------------------------------------------------------------- /Codechef/Lunch_Time/FEB19/AVG.py: -------------------------------------------------------------------------------- 1 | ##Question Link : https://www.codechef.com/LTIME69B/problems/AVG/ 2 | 3 | def main(): 4 | testcases = int(input()) 5 | for test in range(testcases): 6 | n,k,v = map(int,input().split()) 7 | arr = list(map(int,input().split())) 8 | ans = (v*(n+k)-sum(arr))/k 9 | if ans == int(ans) and ans > 0: 10 | print(int(ans)) 11 | else: 12 | print(-1) 13 | 14 | if __name__ == "__main__": 15 | main() 16 | 17 | ##Solution Link : https://www.codechef.com/viewsolution/23193551 18 | -------------------------------------------------------------------------------- /Geeks For Geeks/BASIC/Count nodes of linked list.py: -------------------------------------------------------------------------------- 1 | ## Question link : https://practice.geeksforgeeks.org/problems/count-nodes-of-linked-list/1 2 | 3 | 4 | ''' Please note that it's Function problem i.e. 5 | you need to write your solution in the form of Function(s) only. 6 | Driver Code to call/invoke your function is mentioned above. ''' 7 | 8 | """index is the node which is to be displayed in output 9 | Node is defined as 10 | class Node: 11 | def __init__(self, data): 12 | self.data = data 13 | self.next = None 14 | # Linked List class contains a Node object 15 | class LinkedList: 16 | def __init__(self): 17 | self.head = None 18 | This is method only submission. 19 | You only need to complete below method. 20 | """ 21 | # head is reference to head of linked list 22 | def getCount(head): 23 | # Code here 24 | count = 1 25 | current = head 26 | while current.next != None: 27 | count += 1 28 | current = current.next 29 | return count 30 | 31 | ## Solution Link : https://practice.geeksforgeeks.org/viewSol.php?subId=12635292&pid=700039&user=VikasViki 32 | -------------------------------------------------------------------------------- /Geeks For Geeks/BASIC/Find second largest element.py: -------------------------------------------------------------------------------- 1 | ## Question link : https://practice.geeksforgeeks.org/problems/find-second-largest-element/0 2 | 3 | n = int(input()) 4 | l = list(set(map(int,input().split()))) 5 | if len(l)<2: 6 | print(-1) 7 | else: 8 | l.sort() 9 | print(l[-2]) 10 | 11 | ## Solution link : https://practice.geeksforgeeks.org/viewSol.php?subId=4411217&pid=2040&user=VikasViki 12 | -------------------------------------------------------------------------------- /Geeks For Geeks/BASIC/Find the closest number.py: -------------------------------------------------------------------------------- 1 | ## Question link : https://practice.geeksforgeeks.org/problems/find-the-closest-number/0 2 | 3 | n,k = map(int,input().split()) 4 | l = list(map(int,input().split())) 5 | l.sort() 6 | diff = abs(l[n-1]-k) 7 | ans = l[n-1] 8 | for i in range(n-2,-1,-1): 9 | if abs(l[i]-k) < diff: 10 | ans = l[i] 11 | diff = abs(l[i]-k) 12 | print(ans) 13 | 14 | 15 | ## Solutions link : https://practice.geeksforgeeks.org/viewSol.php?subId=10685030&pid=2805&user=VikasViki 16 | -------------------------------------------------------------------------------- /Geeks For Geeks/BASIC/Immediate Smaller Element.py: -------------------------------------------------------------------------------- 1 | ## Question link : https://practice.geeksforgeeks.org/problems/immediate-smaller-element/0 2 | 3 | n = int(input()) 4 | l = list(map(int,input().split())) 5 | for i in range(n-1): 6 | if l[i+1] < l[i]: 7 | print(l[i+1],end=" ") 8 | else: 9 | print(-1,end=" ") 10 | print(-1) 11 | 12 | 13 | ## Solution link : https://practice.geeksforgeeks.org/viewSol.php?subId=9600515&pid=525&user=VikasViki 14 | -------------------------------------------------------------------------------- /Geeks For Geeks/BASIC/Multiply left and right array sum.py: -------------------------------------------------------------------------------- 1 | ## Question link : https://practice.geeksforgeeks.org/problems/multiply-left-and-right-array-sum/0 2 | n = int(input()) 3 | l = list(map(int,input().split())) 4 | limit = n//2 5 | val1 = sum(l[:limit]) 6 | val2 = sum(l[limit:]) 7 | print(val1*val2) 8 | 9 | ## Solution link : https://practice.geeksforgeeks.org/viewSol.php?subId=5876382&pid=3247&user=VikasViki 10 | -------------------------------------------------------------------------------- /Geeks For Geeks/BASIC/Print an array in Pendulum Arrangement.py: -------------------------------------------------------------------------------- 1 | ## Question link : https://practice.geeksforgeeks.org/problems/print-an-array-in-pendulum-arrangement/0 2 | 3 | n = int(input()) 4 | l = list(map(int,input().split())) 5 | l.sort() 6 | left = [] 7 | right = [] 8 | for i in range(n): 9 | if i%2 == 0: 10 | left.append(l[i]) 11 | else: 12 | right.append(l[i]) 13 | ans = left[::-1] + right 14 | print(*ans) 15 | 16 | ## Solution link : https://practice.geeksforgeeks.org/viewSol.php?subId=10587932&pid=1947&user=VikasViki 17 | -------------------------------------------------------------------------------- /Geeks For Geeks/BASIC/Product of array elements.py: -------------------------------------------------------------------------------- 1 | ## Question link : https://practice.geeksforgeeks.org/problems/product-of-array-element/1 2 | 3 | ''' Please note that it's Function problem i.e. 4 | you need to write your solution in the form of Function(s) only. 5 | Driver Code to call/invoke your function is mentioned above. ''' 6 | 7 | #User function Template for python3 8 | # arr is the array 9 | # n is the number of element in array 10 | # mod= modulo value 11 | def product(arr,n,mod): 12 | # your code here 13 | ans = 1 14 | for value in arr: 15 | ans *= value 16 | return ans%mod 17 | 18 | ## Solution link : https://practice.geeksforgeeks.org/viewSol.php?subId=12966162&pid=700714&user=VikasViki 19 | -------------------------------------------------------------------------------- /Geeks For Geeks/BASIC/Repeated I.Ds.py: -------------------------------------------------------------------------------- 1 | ## Question Link : https://practice.geeksforgeeks.org/problems/repeated-ids/0 2 | 3 | n = int(input()) 4 | l = list(map(int,input().split())) 5 | ans = [] 6 | for i in l: 7 | if i not in ans: 8 | ans.append(i) 9 | print(*ans) 10 | 11 | ## Solution link : https://practice.geeksforgeeks.org/viewSol.php?subId=10709695&pid=2570&user=VikasViki 12 | -------------------------------------------------------------------------------- /Geeks For Geeks/BASIC/Reverse array in groups.py: -------------------------------------------------------------------------------- 1 | ## Question link : https://practice.geeksforgeeks.org/problems/reverse-array-in-groups/0 2 | n,k = map(int,input().split()) 3 | l = list(map(int,input().split())) 4 | ans = [] 5 | for i in range(0,n,k): 6 | start = i 7 | end = i+k 8 | if end >= n: 9 | end = n 10 | ans.extend(reversed(l[start:end])) 11 | print(*ans) 12 | 13 | ## Solution Link : https://practice.geeksforgeeks.org/viewSol.php?subId=10612177&pid=1329&user=VikasViki 14 | -------------------------------------------------------------------------------- /Geeks For Geeks/BASIC/Rotating an Array.py: -------------------------------------------------------------------------------- 1 | ## Question Link : https://practice.geeksforgeeks.org/problems/reversal-algorithm/0 2 | 3 | n = int(input()) 4 | l = list(map(int,input().split())) 5 | d = int(input()) 6 | ans = l[d:] + l[:d] 7 | print(*ans) 8 | 9 | ## Solution Link : https://practice.geeksforgeeks.org/viewSol.php?subId=10576890&pid=924&user=VikasViki 10 | -------------------------------------------------------------------------------- /Geeks For Geeks/BASIC/Search an Element in an array.py: -------------------------------------------------------------------------------- 1 | ## Question link : https://practice.geeksforgeeks.org/problems/search-an-element-in-an-array/0 2 | 3 | n = int(input()) 4 | l = list(map(int,input().split())) 5 | x = int(input()) 6 | for i in range(n): 7 | if l[i] == x: 8 | print(i) 9 | break 10 | else: 11 | print(-1) 12 | 13 | ## Solution Link : https://practice.geeksforgeeks.org/viewSol.php?subId=7643246&pid=77&user=VikasViki 14 | -------------------------------------------------------------------------------- /Geeks For Geeks/BASIC/Sort in specific order.py: -------------------------------------------------------------------------------- 1 | ## Question link : https://practice.geeksforgeeks.org/problems/sort-in-specific-order/0 2 | 3 | n = int(input()) 4 | l = sorted(list(map(int,input().split()))) 5 | odd = [] 6 | even = [] 7 | for i in l: 8 | if i%2 == 0: 9 | even.append(i) 10 | else: 11 | odd.append(i) 12 | ans = odd[::-1] + even 13 | print(*ans) 14 | 15 | ## Solution Link : https://practice.geeksforgeeks.org/viewSol.php?subId=10722944&pid=1696&user=VikasViki 16 | -------------------------------------------------------------------------------- /Geeks For Geeks/BASIC/Space Seperated - Python.py: -------------------------------------------------------------------------------- 1 | ## Question link : https://practice.geeksforgeeks.org/problems/space-seperated-python/1 2 | 3 | 4 | ''' Please note that it's Function problem i.e. 5 | you need to write your solution in the form of Function(s) only. 6 | Driver Code to call/invoke your function is mentioned above. ''' 7 | 8 | #User function Template for python3 9 | # Function to print words with spaces 10 | def print_fun(): 11 | # Your code here 12 | # Do not use space in the string 13 | # try to use seperator 14 | print("Geeks","For","Geeks") 15 | 16 | ## Solution link : https://practice.geeksforgeeks.org/viewSol.php?subId=12320158&pid=700932&user=VikasViki 17 | -------------------------------------------------------------------------------- /Geeks For Geeks/BASIC/Start Coding - Python.py: -------------------------------------------------------------------------------- 1 | ## Question link : https://practice.geeksforgeeks.org/problems/start-coding-python/1 2 | 3 | ''' Please note that it's Function problem i.e. 4 | you need to write your solution in the form of Function(s) only. 5 | Driver Code to call/invoke your function is mentioned above. ''' 6 | 7 | #User function Template for python3 8 | def print_fun(): 9 | 10 | # Your code here 11 | # Please follow proper indentation 12 | print("Hello World") 13 | 14 | ## Solution link : https://practice.geeksforgeeks.org/viewSol.php?subId=12320112&pid=700930&user=VikasViki 15 | -------------------------------------------------------------------------------- /Geeks For Geeks/BASIC/Transform to prime.py: -------------------------------------------------------------------------------- 1 | ## Question link : https://practice.geeksforgeeks.org/problems/transform-to-prime/0 2 | 3 | prime[0] = 0 4 | prime[1] = 0 5 | p = 2 6 | while p*p <= 1000000: 7 | if prime[p]: 8 | for i in range(2*p,1000001,p): 9 | prime[i] = 0 10 | p += 1 11 | 12 | 13 | for _ in range(int(input())): 14 | n = int(input()) 15 | l = list(map(int,input().split())) 16 | ans = sum(l) 17 | count = 0 18 | while not prime[ans]: 19 | ans += 1 20 | count += 1 21 | print(count) 22 | 23 | ## Solution link : https://practice.geeksforgeeks.org/viewSol.php?subId=10658684&pid=2452&user=VikasViki 24 | -------------------------------------------------------------------------------- /Geeks For Geeks/EASY/Chocolate Distribution Problem.py: -------------------------------------------------------------------------------- 1 | ## Question link : https://practice.geeksforgeeks.org/problems/chocolate-distribution-problem/0 2 | n = int(input()) 3 | l = sorted(list(map(int,input().split()))) 4 | m = int(input()) 5 | ans = 10**18 6 | for i in range(0,n-m+1): 7 | temp = l[i+m-1] - l[i] 8 | if temp < ans: 9 | ans = temp 10 | if ans == 0: 11 | break 12 | print(ans) 13 | 14 | ## Solution link : https://practice.geeksforgeeks.org/viewSol.php?subId=10694773&pid=1571&user=VikasViki 15 | -------------------------------------------------------------------------------- /Geeks For Geeks/EASY/Index Of an Extra Element.py: -------------------------------------------------------------------------------- 1 | ## Questions link : https://practice.geeksforgeeks.org/problems/index-of-an-extra-element/1 2 | 3 | Please note that it's Function problem i.e. 4 | you need to write your solution in the form of Function(s) only. 5 | Driver Code to call/invoke your function would be added by GfG's Online Judge.*/ 6 | 7 | 8 | /*Complete the function below*/ 9 | int findExtra(int a[],int b[],int n) 10 | { 11 | //add code here. 12 | int index = 0; 13 | for (int i = 0;i= leader: 11 | ans.append(l[i]) 12 | leader = l[i] 13 | count += 1 14 | for i in range(count-1,-1,-1): 15 | print(ans[i],end=" ") 16 | print() 17 | 18 | ## Solution link : https://practice.geeksforgeeks.org/viewSol.php?subId=10645814&pid=623&user=VikasViki 19 | -------------------------------------------------------------------------------- /Geeks For Geeks/EASY/SP - Palindrome Family.py: -------------------------------------------------------------------------------- 1 | ## Question link : https://practice.geeksforgeeks.org/problems/sp-palindrome-family/0 2 | 3 | ##Function to check whether the string is palindrome 4 | def pal(s): 5 | if string[:] == string[::-1]: 6 | return True 7 | else: 8 | return False 9 | 10 | for _ in range(int(input())): 11 | s = input() 12 | if pal(s): 13 | print("PARENT") 14 | else: 15 | even = "".join([s[i] for i in range(len(s)) if i%2 != 0]) 16 | odd = "".join([s[i] for i in range(len(s)) if i%2 == 0]) 17 | pal_even = pal(even) 18 | pal_odd = pal(odd) 19 | if pal_even and pal_odd: 20 | print("TWIN") 21 | elif pal_even: 22 | print("EVEN") 23 | elif pal_odd: 24 | print("ODD") 25 | else: 26 | print("ALIEN") 27 | 28 | ## Solution link : https://practice.geeksforgeeks.org/viewSol.php?subId=7357149&pid=3507&user=VikasViki 29 | -------------------------------------------------------------------------------- /Geeks For Geeks/EASY/Sort an array of 0s, 1s and 2s.py: -------------------------------------------------------------------------------- 1 | ##Question link : https://practice.geeksforgeeks.org/problems/sort-an-array-of-0s-1s-and-2s/0 2 | n = int(input()) 3 | l = list(map(int,input().split())) 4 | l.sort() 5 | print(*l) 6 | ##Solution link : https://practice.geeksforgeeks.org/viewSol.php?subId=9594302&pid=341&user=VikasViki 7 | -------------------------------------------------------------------------------- /Geeks For Geeks/EASY/Subarray with given sum.py: -------------------------------------------------------------------------------- 1 | ## QUESTION LINK : https://practice.geeksforgeeks.org/problems/subarray-with-given-sum/0 2 | 3 | def main(): 4 | testcases = int(input()) 5 | for _ in range(testcases): 6 | arr_size, desired_sum = map(int, input().split()) 7 | arr = list(map(int, input().split())) 8 | start_index = index = 0 9 | curr_sum = 0 10 | while index < arr_size: 11 | curr_sum += arr[index] 12 | while curr_sum > desired_sum: 13 | curr_sum -= arr[start_index] 14 | start_index += 1 15 | if curr_sum == desired_sum: 16 | print(start_index+1, index+1) 17 | break 18 | index += 1 19 | if curr_sum != desired_sum: 20 | print(-1) 21 | 22 | if __name__ == '__main__': 23 | main() 24 | 25 | ## SOLUTION LINK : https://practice.geeksforgeeks.org/viewSol.php?subId=271cf09e4af2975824e138d5e0cba5e8&pid=590&user=VikasViki 26 | -------------------------------------------------------------------------------- /Geeks For Geeks/EASY/Sum of given range.py: -------------------------------------------------------------------------------- 1 | ## Question link : https://practice.geeksforgeeks.org/problems/sum-of-given-range/1 2 | 3 | 4 | ''' Please note that it's Function problem i.e. 5 | you need to write your solution in the form of Function(s) only. 6 | Driver Code to call/invoke your function is mentioned above. ''' 7 | 8 | #User function Template for python3 9 | def getSum(arr,low,high): 10 | #Add code here 11 | print(sum(arr[low:high+1])) 12 | 13 | ## Solution link : https://practice.geeksforgeeks.org/viewSol.php?subId=12926043&pid=700531&user=VikasViki 14 | -------------------------------------------------------------------------------- /Geeks For Geeks/EASY/Triangular Number.py: -------------------------------------------------------------------------------- 1 | ## Question link : https://practice.geeksforgeeks.org/problems/triangular-number/0 2 | for number in range(1000000): 3 | value = (number*(number+1))//2 4 | if value >= 10000000: 5 | break 6 | triangular_numbers.add(value) 7 | 8 | no_of_test = int(input()) 9 | for test in range(no_of_test): 10 | number = int(input()) 11 | if number in triangular_numbers: 12 | print(1) 13 | else: 14 | print(0) 15 | 16 | ## Solution link : https://practice.geeksforgeeks.org/viewSol.php?subId=12925928&pid=517&user=VikasViki 17 | -------------------------------------------------------------------------------- /Geeks For Geeks/HARD/Return two prime numbers.py: -------------------------------------------------------------------------------- 1 | ## Question Link : https://practice.geeksforgeeks.org/problems/return-two-prime-numbers/0 2 | 3 | prime[0] = 0 4 | prime[1] = 0 5 | number = 2 6 | while number*number <= 1000000: 7 | if prime[number]: 8 | for numbers_multiple in range(2*number,1000000,number): 9 | prime[numbers_multiple] = 0 10 | number += 1 11 | 12 | no_of_test = int(input()) 13 | for test in range(no_of_test): 14 | n = int(input()) 15 | val1 = 3 16 | val2 = n-val1 17 | while True: 18 | if prime[val1] and prime[val2]: 19 | print(val1,val2) 20 | break 21 | for index in range(val1+1,1000000): 22 | if prime[index]: 23 | val1 = index 24 | val2 = n - val1 25 | break 26 | 27 | ## Solution link : https://practice.geeksforgeeks.org/viewSol.php?subId=12925271&pid=425&user=VikasViki 28 | -------------------------------------------------------------------------------- /Geeks For Geeks/MEDIUM/Case-specific Sorting of Strings.py: -------------------------------------------------------------------------------- 1 | ## Question link : https://practice.geeksforgeeks.org/problems/case-specific-sorting-of-strings/0 2 | 3 | for test in range(no_of_test): 4 | 5 | string_length = int(input()) 6 | case = [] 7 | lower_characters = [] 8 | upper_characters = [] 9 | string = input() 10 | 11 | for index in range(string_length): 12 | if string[index].islower(): 13 | case.append(0) 14 | lower_characters.append(string[index]) 15 | else: 16 | case.append(1) 17 | upper_characters.append(string[index]) 18 | lower_characters.sort() 19 | upper_characters.sort() 20 | 21 | sorted_string = "" 22 | lower_index = 0 23 | upper_index = 0 24 | 25 | for value in case: 26 | if value: 27 | sorted_string += upper_characters[upper_index] 28 | upper_index += 1 29 | else: 30 | sorted_string += lower_characters[lower_index] 31 | lower_index += 1 32 | 33 | print(sorted_string) 34 | 35 | ## Solution link : https://practice.geeksforgeeks.org/viewSol.php?subId=12952455&pid=331&user=VikasViki 36 | -------------------------------------------------------------------------------- /Geeks For Geeks/MEDIUM/Excel Sheet | Part - 1.py: -------------------------------------------------------------------------------- 1 | ## Question link : https://practice.geeksforgeeks.org/problems/excel-sheet/0 2 | 3 | for _ in range(no_of_testcases): 4 | ans = "" 5 | number = int(input()) 6 | while number > 0: 7 | remainder = number%26 8 | if remainder == 0: 9 | ans += "Z" 10 | number = number // 26 - 1 11 | else: 12 | ans += chr(remainder + 64) 13 | number = number // 26 14 | print(ans[::-1]) 15 | 16 | ## Solution link : https://practice.geeksforgeeks.org/viewSol.php?subId=11903425&pid=117&user=VikasViki 17 | -------------------------------------------------------------------------------- /Geeks For Geeks/MEDIUM/Find Prime numbers in a range.py: -------------------------------------------------------------------------------- 1 | ## Question link : https://practice.geeksforgeeks.org/problems/find-prime-numbers-in-a-range/0 2 | 3 | prime[0] = 0 4 | prime[1] = 0 5 | number = 2 6 | while number*number <= 1000002: 7 | if prime[number]: 8 | for multiples in range(2*number, 1000002, number): 9 | prime[multiples] = 0 10 | number += 1 11 | 12 | no_of_test = int(input()) 13 | for test in range(no_of_test): 14 | start, end = map(int,input().split()) 15 | for value in range(start,end+1): 16 | if prime[value]: 17 | print(value,end=" ") 18 | print() 19 | 20 | ## Solution link : https://practice.geeksforgeeks.org/viewSol.php?subId=12952208&pid=374&user=VikasViki 21 | -------------------------------------------------------------------------------- /Geeks For Geeks/MEDIUM/Kth smallest element.py: -------------------------------------------------------------------------------- 1 | ## Question link : https://practice.geeksforgeeks.org/problems/kth-smallest-element/0 2 | 3 | for test in range(no_of_test): 4 | size_of_arr = int(input()) 5 | arr = list(map(int,input().split())) 6 | k = int(input()) 7 | arr.sort() 8 | print(arr[k-1]) 9 | 10 | ## Solution link : https://practice.geeksforgeeks.org/viewSol.php?subId=12924732&pid=1301&user=VikasViki 11 | -------------------------------------------------------------------------------- /Geeks For Geeks/MEDIUM/Multiply two strings.py: -------------------------------------------------------------------------------- 1 | ## Question link : https://practice.geeksforgeeks.org/problems/multiply-two-strings/1 2 | 3 | 4 | ''' Please note that it's Function problem i.e. 5 | you need to write your solution in the form of Function(s) only. 6 | Driver Code to call/invoke your function is mentioned above. ''' 7 | 8 | #User function Template for python3 9 | def multiply(a,b): 10 | #add code here 11 | print(int(a)*int(b)) 12 | 13 | ## Solution link : https://practice.geeksforgeeks.org/viewSol.php?subId=10587980&pid=700383&user=VikasViki 14 | -------------------------------------------------------------------------------- /Geeks For Geeks/MEDIUM/Nearly Sorted Algorithm.py: -------------------------------------------------------------------------------- 1 | ## Question link : https://practice.geeksforgeeks.org/problems/nearly-sorted-algorithm/0 2 | 3 | no_of_test = int(input()) 4 | for test in range(no_of_test): 5 | n,k = map(int,input().split()) 6 | array = list(map(int,input().split())) 7 | array.sort() 8 | print(*array) 9 | 10 | ## Solution link : https://practice.geeksforgeeks.org/viewSol.php?subId=12985633&pid=1967&user=VikasViki 11 | -------------------------------------------------------------------------------- /Geeks For Geeks/MEDIUM/Sum of bit differences.py: -------------------------------------------------------------------------------- 1 | ## Question link : https://practice.geeksforgeeks.org/problems/sum-of-bit-differences/0 2 | 3 | def bit_difference(number1, number2): 4 | xor_of_numbers = number1 ^ number2 5 | no_of_diff_bits = bin(xor_of_numbers).count('1') 6 | return no_of_diff_bits 7 | 8 | no_of_test = int(input()) 9 | 10 | for test in range(no_of_test): 11 | array_size = int(input()) 12 | array = list(map(int,input().split())) 13 | sum_of_bit_diff = 0 14 | 15 | for index1 in range(array_size): 16 | for index2 in range(index1+1,array_size): 17 | 18 | sum_of_bit_diff += bit_difference(array[index1],array[index2]) 19 | 20 | print(sum_of_bit_diff*2) 21 | 22 | ## Solution link : https://practice.geeksforgeeks.org/viewSol.php?subId=12985586&pid=345&user=VikasViki 23 | -------------------------------------------------------------------------------- /Geeks For Geeks/SCHOOL/Print alternate elements of an array.py: -------------------------------------------------------------------------------- 1 | ## Question Link : https://practice.geeksforgeeks.org/problems/print-alternate-elements-of-an-array/1 2 | 3 | 4 | ''' Please note that it's Function problem i.e. 5 | you need to write your solution in the form of Function(s) only. 6 | Driver Code to call/invoke your function is mentioned above. ''' 7 | 8 | #User function Template for python3 9 | # arr is the array 10 | # n is the number of elements in array 11 | def printAl(arr,n): 12 | # your code here 13 | for index in range(0,n,2): 14 | print(arr[index],end=" ") 15 | 16 | ## Solution Link : https://practice.geeksforgeeks.org/viewSol.php?subId=12549915&pid=700712&user=VikasViki 17 | -------------------------------------------------------------------------------- /Geeks For Geeks/SCHOOL/Reverse an Array.py: -------------------------------------------------------------------------------- 1 | ## Question Link : https://practice.geeksforgeeks.org/problems/reverse-an-array/0 2 | 3 | n = int(input()) 4 | l = list(map(int,input().split())) 5 | for i in range(n-1,-1,-1): 6 | print(l[i],end=" ") 7 | print() 8 | 9 | ##Solution Link : https://practice.geeksforgeeks.org/viewSol.php?subId=10681879&pid=78&user=VikasViki 10 | -------------------------------------------------------------------------------- /Hacker Blocks/GENERAL/Rotate Image: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | matrix = [] 3 | for _ in range(n): 4 | temp = list(map(int,input().split())) 5 | matrix.append(temp) 6 | for row in range(n//2): 7 | for col in range(row,n-row-1): 8 | temp = matrix[row][col] 9 | matrix[row][col] = matrix[col][n-row-1] 10 | matrix[col][n-row-1] = matrix[n-row-1][n-col-1] 11 | matrix[n-row-1][n-col-1] = matrix[n-col-1][row] 12 | matrix[n-col-1][row] = temp 13 | for row in matrix: 14 | print(*row) 15 | -------------------------------------------------------------------------------- /InterviewBit/Day 17 : Two Pointers/Assignment/Count of pairs with the given sum: -------------------------------------------------------------------------------- 1 | ## Question 2 | 3 | """ 4 | Count of pairs with the given sum 5 | Given a sorted array of distinct integers A and an integer B, find and return how many pair of integers ( A[i], A[j] ) such that i != j have sum equal to B. 6 | Input Format 7 | The first argument given is the integer array A. 8 | The second argument given is integer B. 9 | Output Format 10 | Return the number of pairs for which sum is equal to B. 11 | Constraints 12 | 1 <= length of the array <= 100000 13 | 1 <= A[i] <= 10^9 14 | 1 <= B <= 10^9 15 | For Example 16 | Input 1: 17 | A = [1, 2, 3, 4, 5] 18 | B = 5 19 | Output 1: 20 | 2 21 | 22 | Input 2: 23 | A = [5, 10, 20, 100, 105] 24 | B = 110 25 | Output 2: 26 | 2 27 | """ 28 | 29 | ## Solution 30 | 31 | class Solution: 32 | # @param A : list of integers 33 | # @param B : integer 34 | # @return an integer 35 | def solve(self, A, B): 36 | start = 0 37 | end = len(A)-1 38 | pairs_count = 0 39 | while start < end: 40 | temp_sum = A[start]+A[end] 41 | if temp_sum > B: 42 | end -= 1 43 | elif temp_sum < B: 44 | start += 1 45 | else: 46 | pairs_count += 1 47 | start += 1 48 | end -= 1 49 | return pairs_count 50 | -------------------------------------------------------------------------------- /InterviewBit/Day 2: Array and Math/Assignment/Closest MinMax: -------------------------------------------------------------------------------- 1 | ## Question 2 | 3 | """ 4 | Closest MinMax 5 | Given an array of size N. Find the size of the smallest subarray such that it contains atleast one occurrence of the maximum value of the array and atleast one occurrence of the minimum value of the array. Constraints: 6 | 1. 1 <= N <= 2000 7 | Input Format An integer array. Output Format Length of the smallest subarray which has atleast one occurrence of minimum and maximum element of the array Example Input 8 | Array:[1 3 5 2 4 3] 9 | Example Output 10 | 3 11 | Explanation Choose the subarray starting from the 0th index and ending at 2nd index which is of size 3. 12 | """ 13 | 14 | ## Solution 15 | 16 | class Solution: 17 | # @param A : list of integers 18 | # @return an integer 19 | def solve(self, A): 20 | 21 | A_length = len(A) 22 | 23 | if A_length == 1: 24 | return 1 25 | 26 | min_val = max_val = A[0] 27 | 28 | for index in range(1,A_length): 29 | if A[index] < min_val: 30 | min_val = A[index] 31 | elif A[index] > max_val: 32 | max_val = A[index] 33 | 34 | ans = float('inf') 35 | min_index = ans 36 | max_index = ans 37 | 38 | for index in range(A_length): 39 | 40 | if A[index] == min_val: 41 | min_index = index 42 | 43 | if A[index] == max_val: 44 | max_index = index 45 | 46 | ans = min(ans, abs(max_index-min_index)+1) 47 | 48 | return ans 49 | 50 | 51 | -------------------------------------------------------------------------------- /InterviewBit/Day 6/Assignment/Delete Elements: -------------------------------------------------------------------------------- 1 | ## Question 2 | 3 | """ 4 | Delete Elements 5 | Problem Description 6 | Given an integer array A of size N. 7 | Find the minimum number of elements that need to be removed such that the GCD of the resulting array becomes 1. 8 | 9 | If not possible then return -1. 10 | 11 | 12 | 13 | Problem Constraints 14 | 1 <= N <= 100000 15 | 1 <= A[i] <= 1e9 16 | 17 | 18 | 19 | Input Format 20 | Input contains a single integer array A 21 | 22 | 23 | 24 | Output Format 25 | Return an integer 26 | 27 | 28 | Example Input 29 | Input 1: 30 | A = [7, 2, 5] 31 | 32 | 33 | 34 | Example Output 35 | Output 1: 36 | 0 37 | 38 | 39 | 40 | Example Explanation 41 | Explanation 1: 42 | GCD of the array A is 1. 43 | so, the number of elements to be removed is 0. 44 | """ 45 | 46 | ## Solution 47 | 48 | class Solution: 49 | # @param A : list of integers 50 | # @return an integer 51 | def gcd(self, A, B): 52 | while B: 53 | A, B = B, A % B 54 | return A 55 | 56 | def solve(self, A): 57 | arr_gcd = A[0] 58 | for ele in A[1:]: 59 | arr_gcd = self.gcd(arr_gcd, ele) 60 | if arr_gcd == 1: 61 | return 0 62 | return -1 63 | -------------------------------------------------------------------------------- /InterviewBit/Day 6/Assignment/Delete one: -------------------------------------------------------------------------------- 1 | ## Question 2 | 3 | """ 4 | Problem Description 5 | Given an integer array A of size N. You have to delete one element such that the GCD(Greatest common divisor) of the remaining array is maximum. 6 | 7 | Find the maximum value of GCD. 8 | 9 | 10 | Problem Constraints 11 | 2 <= N <= 105 12 | 1 <= A[i] <= 109 13 | 14 | 15 | Input Format 16 | First argument is an integer array A. 17 | 18 | 19 | Output Format 20 | Return an integer denoting the maximum value of GCD. 21 | 22 | 23 | Example Input 24 | Input 1: 25 | A = [12, 15, 18] 26 | Input 2: 27 | A = [5, 15, 30] 28 | 29 | 30 | 31 | Example Output 32 | Output 1: 33 | 6 34 | Output 2: 35 | 15 36 | 37 | 38 | 39 | Example Explanation 40 | Explanation 1: 41 | 42 | If you delete 12, gcd will be 3. 43 | If you delete 15, gcd will be 6. 44 | If you delete 18, gcd will 3. 45 | Maximum vallue of gcd is 6. 46 | Explanation 2: 47 | If you delete 5, gcd will be 15. 48 | If you delete 15, gcd will be 5. 49 | If you delete 30, gcd will be 5. 50 | """ 51 | 52 | ## Solution 53 | 54 | class Solution: 55 | # @param A : list of integers 56 | # @return an integer 57 | def gcd(self, A, B): 58 | while B: 59 | A, B = B, A%B 60 | return A 61 | 62 | def solve(self, A): 63 | A_length = len(A) 64 | prefix_gcd = [0] * A_length 65 | suffix_gcd = [0] * A_length 66 | 67 | prefix_gcd[0] = A[0] 68 | for index in range(1, A_length): 69 | prefix_gcd[index] = self.gcd(prefix_gcd[index-1], A[index]) 70 | 71 | suffix_gcd[-1] = A[-1] 72 | for index in range(A_length-2, -1, -1): 73 | suffix_gcd[index] = self.gcd(suffix_gcd[index+1], A[index]) 74 | 75 | ele_to_remove = A[0] 76 | max_gcd = suffix_gcd[1] 77 | 78 | for index in range(1, A_length-1): 79 | temp_gcd = self.gcd(prefix_gcd[index-1], suffix_gcd[index+1]) 80 | if temp_gcd > max_gcd: 81 | max_gcd = temp_gcd 82 | ele_to_remove = A[index] 83 | 84 | if prefix_gcd[-2] > max_gcd: 85 | max_gcd = prefix_gcd[-2] 86 | ele_to_remove = A[-1] 87 | 88 | # print(prefix_gcd) 89 | # print(suffix_gcd) 90 | # print(max_gcd, ele_to_remove) 91 | return max_gcd 92 | -------------------------------------------------------------------------------- /InterviewBit/Day 6/Assignment/Divisor Game: -------------------------------------------------------------------------------- 1 | ## Question 2 | 3 | """ 4 | Divisor game 5 | Problem Description 6 | Scooby has 3 three integers A, B and C. Scooby calls a positive integer special if it is divisible by B and it is divisible by C. You need to tell number of special integers less than or equal to A. 7 | 8 | 9 | Problem Constraints 10 | 1 <= A, B, C <= 1000000000 11 | 12 | 13 | Input Format 14 | A positive integer A 15 | A positive integer B 16 | A positive integer C 17 | 18 | 19 | Output Format 20 | One integer corresponding to the number of special integers less than or equal to A. 21 | 22 | 23 | Example Input 24 | A=12, B=3, C=2 25 | 26 | 27 | Example Output 28 | 2 29 | 30 | 31 | Example Explanation 32 | The two integers divisible by 2 and 3 and less than or equal to 12 are 6,12 33 | """ 34 | 35 | 36 | ## Partially Solved Solution 37 | 38 | class Solution: 39 | # @param A : integer 40 | # @param B : integer 41 | # @param C : integer 42 | # @return an integer 43 | def solve(self, A, B, C): 44 | factor = B * C 45 | divisors_count = 0 46 | for num in range(1, A+1): 47 | if not num%factor: 48 | divisors_count += 1 49 | return divisors_count 50 | 51 | 52 | ## Optimized Solution 53 | 54 | class Solution: 55 | # @param A : integer 56 | # @param B : integer 57 | # @param C : integer 58 | # @return an integer 59 | def gcd(self, A, B): 60 | while B: 61 | A, B = B, A%B 62 | return A 63 | 64 | def solve(self, A, B, C): 65 | lcm = (B * C)// self.gcd(B, C) 66 | return A//lcm 67 | -------------------------------------------------------------------------------- /InterviewBit/Day 6/Assignment/Greatest Common Divisor: -------------------------------------------------------------------------------- 1 | ## Question 2 | 3 | """ 4 | Greatest Common Divisor 5 | Problem Description 6 | Given 2 non negative integers A and B, find gcd(A, B) GCD of 2 integers A and B is defined as the greatest integer g such that g is a divisor of both A and B. Both A and B fit in a 32 bit signed integer. Note: DO NOT USE LIBRARY FUNCTIONS. 7 | 8 | 9 | Problem Constraints 10 | 0 <= A, B <= 109 11 | 12 | 13 | Input Format 14 | First argument is an integer A. 15 | Second argument is an integer B. 16 | 17 | 18 | Output Format 19 | Return an integer denoting the gcd(A, B). 20 | 21 | 22 | Example Input 23 | Input 1: 24 | A = 6 25 | B = 3 26 | 27 | 28 | Example Output 29 | Output 1: 30 | 3 31 | 32 | 33 | Example Explanation 34 | Explanation 1: 35 | GCD(3, 6) = 3 as 3 divides both 3 and 6. 36 | 37 | """ 38 | 39 | ## Solution 40 | 41 | class Solution: 42 | # @param A : integer 43 | # @param B : integer 44 | # @return an integer 45 | def gcd(self, A, B): 46 | if B: 47 | return self.gcd(B, A%B) 48 | else: 49 | return A 50 | -------------------------------------------------------------------------------- /InterviewBit/Day 6/Assignment/Pubg: -------------------------------------------------------------------------------- 1 | ## Question 2 | 3 | """ 4 | Pubg 5 | Problem Description 6 | There are N players each with strength A[i]. when player i attack player j, player j strength reduces to max(0, A[j]-A[i]). When a player's strength reaches zero, it loses the game and the game continues in the same manner among other players until only 1 survivor remains. 7 | 8 | Can you tell the minimum health last surviving person can have? 9 | 10 | 11 | Problem Constraints 12 | 1 <= N <= 100000 13 | 1 <= A[i] <= 1000000 14 | 15 | 16 | Input Format 17 | First and only argument of input contains a single integer array A. 18 | 19 | 20 | Output Format 21 | Return a single integer denoting minimum health of last person. 22 | 23 | Example Input 24 | Input 1: 25 | A = [6, 4] 26 | Input 2: 27 | A = [2, 3, 4] 28 | 29 | Example Output 30 | Output 1: 31 | 2 32 | Output 2: 33 | 1 34 | """ 35 | 36 | ## Solution 37 | 38 | class Solution: 39 | # @param A : list of integers 40 | # @return an integer 41 | def gcd(self, A, B): 42 | while B: 43 | A, B = B, A % B 44 | return A 45 | 46 | def solve(self, A): 47 | A_length = len(A) 48 | 49 | if A_length == 1: 50 | return A[0] 51 | 52 | min_health = self.gcd(A[0], A[1]) 53 | for ele in A: 54 | min_health = self.gcd(min_health, ele) 55 | return min_health 56 | 57 | ## Optimized 58 | 59 | class Solution: 60 | # @param A : list of integers 61 | # @return an integer 62 | def gcd(self, A, B): 63 | while B: 64 | A, B = B, A % B 65 | return A 66 | 67 | def solve(self, A): 68 | A_length = len(A) 69 | 70 | min_health = A[0] 71 | for index in range(1,A_length): 72 | min_health = self.gcd(min_health, A[index]) 73 | return min_health 74 | 75 | -------------------------------------------------------------------------------- /InterviewBit/Day 6/Homework/A, B and Modulo: -------------------------------------------------------------------------------- 1 | ## Question 2 | 3 | """ 4 | A, B and Modulo 5 | Problem Description 6 | Given two integers A and B, find the greatest possible positive M, such that A % M = B % M. 7 | 8 | 9 | Problem Constraints 10 | 1 <= A, B <= 109 11 | A != B 12 | 13 | 14 | Input Format 15 | The first argument given is the integer, A. 16 | The second argument given is the integer, B. 17 | 18 | 19 | Output Format 20 | Return an integer denoting greatest possible positive M. 21 | 22 | 23 | Example Input 24 | Input 1: 25 | A = 1 26 | B = 2 27 | Input 2: 28 | A = 5 29 | B = 10 30 | 31 | 32 | 33 | Example Output 34 | Output 1: 35 | 1 36 | Output 2: 37 | 5 38 | 39 | 40 | 41 | Example Explanation 42 | Explanation 1: 43 | 1 is the largest value of M such that A % M == B % M. 44 | Explanation 2: 45 | For M = 5, A % M = 0 and B % M = 0. 46 | 47 | No value greater than M = 5, satisfies the condition. 48 | """ 49 | 50 | ## Solution 51 | 52 | class Solution: 53 | # @param A : integer 54 | # @param B : integer 55 | # @return an integer 56 | def solve(self, A, B): 57 | return abs(A-B) 58 | -------------------------------------------------------------------------------- /InterviewBit/Day 6/Homework/Consecutive Number Sum: -------------------------------------------------------------------------------- 1 | ## Question 2 | 3 | """ 4 | Problem Description 5 | Given an integer A. Return number of ways we can write A as a sum of consecutive positive integers. 6 | 7 | 8 | Problem Constraints 9 | 1 <= A <= 109 10 | 11 | 12 | Input Format 13 | The first argument given is the integer A. 14 | 15 | 16 | Output Format 17 | Return number of ways we can write A as a sum of consecutive positive integers. 18 | 19 | 20 | Example Input 21 | A = 9 22 | 23 | 24 | Example Output 25 | 3 26 | 27 | 28 | Example Explanation 29 | A = 9 30 | A = 2 + 3 + 4 31 | A = 5 + 4 32 | """ 33 | 34 | ## Solution 35 | 36 | class Solution: 37 | # @param A : integer 38 | # @return an integer 39 | def solve(self, A): 40 | ways_count = 1 41 | l = 1 42 | """ 43 | The idea is to represent N as a sequence of length L+1 as: 44 | => N = a + (a+1) + (a+2) + .. + (a+L) 45 | => N = (L+1)*a + (1 + 2 + 3 + ... L) 46 | => N = (L+1)*a + (L*(L+1))/2 # 47 | => a = (N- L*(L+1)/2)/(L+1) 48 | We substitute the values of L starting from 1 till L*(L+1)/2 < N 49 | If we get 'a' as a natural number then the solution should be counted. 50 | """ 51 | while (l*(l+1))/2 < A: 52 | start = (A - (l*(l+1))/2)/(l+1) 53 | if start == int(start): 54 | ways_count += 1 55 | l += 1 56 | return ways_count 57 | -------------------------------------------------------------------------------- /InterviewBit/Day 6/Homework/Enumerating GCD: -------------------------------------------------------------------------------- 1 | ## Question 2 | 3 | """ 4 | Problem Description 5 | You are given a number A and a number B. Greatest Common Divisor (GCD) of all numbers between A and B inclusive is taken (GCD(A, A+1, A+2 ... B)). As this problem looks a bit easy, it is given that numbers A and B can be in the range of 10100. You have to return the value of GCD found. Greatest common divisor of 2 numbers A and B is the largest number D that divides both A and B perfectly. 6 | 7 | 8 | Problem Constraints 9 | 1 <= A <= B <= 10100 10 | 11 | 12 | Input Format 13 | First argument is a string denoting A. Second argument is a string denoting B. 14 | 15 | 16 | Output Format 17 | Return a string which contains the digits of the integer which represents the GCD. The returned string should not have any leading zeroes. 18 | 19 | 20 | Example Input 21 | A = "1" 22 | B = "3" 23 | 24 | 25 | Example Output 26 | 1 27 | 28 | 29 | Example Explanation 30 | Greatest divisor that divides both 1 and 3 is 1. 31 | """ 32 | 33 | ## Solution 34 | 35 | class Solution: 36 | # @param A : string 37 | # @param B : string 38 | # @return a strings 39 | def solve(self, A, B): 40 | if A == B: 41 | return A 42 | else: 43 | return 1 44 | -------------------------------------------------------------------------------- /InterviewBit/Day 6/Homework/Trailing Zeros in Factorial: -------------------------------------------------------------------------------- 1 | ## Question 2 | 3 | """" 4 | Trailing Zeros in Factorial 5 | Problem Description 6 | Given an integer A, return the number of trailing zeroes in A! i.e. factorial of A. Note: Your solution should run in logarithmic time complexity. 7 | 8 | 9 | Problem Constraints 10 | 1 <= A <= 109 11 | 12 | 13 | Input Format 14 | First and only argument is a single integer A. 15 | 16 | 17 | Output Format 18 | Return a single integer denoting number of zeroes. 19 | 20 | 21 | Example Input 22 | Input 1 23 | A = 5 24 | Input 2: 25 | A = 6 26 | 27 | 28 | 29 | Example Output 30 | Output 1: 31 | 1 32 | Output 2: 33 | 1 34 | 35 | 36 | 37 | Example Explanation 38 | Explanation 1: 39 | A! = 120. 40 | Number of trailing zeros = 1. So, return 1. 41 | Explanation 2: 42 | A! = 720 43 | Number of trailing zeros = 1. So, return 1. 44 | """ 45 | 46 | ## Solution 47 | 48 | class Solution: 49 | # @param A : integer 50 | # @return an integer 51 | def trailingZeroes(self, A): 52 | 53 | zeros_count = 0 54 | num = A 55 | quotient = 1 56 | 57 | while quotient > 0: 58 | quotient = num // 5 59 | zeros_count += quotient 60 | num = quotient 61 | 62 | # print("Zeros Count ", zeros_count) 63 | return zeros_count 64 | 65 | -------------------------------------------------------------------------------- /InterviewBit/Day 8/Assignment/Count of divisors for multiple queries: -------------------------------------------------------------------------------- 1 | ## Question 2 | 3 | """ 4 | Count of divisors for multiple queries 5 | Problem Description 6 | Given an array of integers A, find and return the count of divisors of each element of the array. NOTE: Order of the resultant array should be same as the input array. 7 | 8 | 9 | Problem Constraints 10 | 1 <= length of the array <= 100000 11 | 1 <= A[i] <= 106 12 | 13 | 14 | Input Format 15 | The only argument given is the integer array A. 16 | 17 | 18 | Output Format 19 | Return the count of divisors of each element of the array in the form of an array. 20 | 21 | 22 | Example Input 23 | Input 1: 24 | A = [2, 3, 4, 5] 25 | Input 2: 26 | A = [8, 9, 10] 27 | 28 | 29 | Example Output 30 | Output 1: 31 | [2, 2, 3, 2] 32 | Output 1: 33 | [4, 3, 4] 34 | 35 | 36 | Example Explanation 37 | Explanation 1: 38 | The number of divisors of 2 : [1, 2], 3 : [1, 3], 4 : [1, 2, 4], 5 : [1, 5] 39 | So the count will be [2, 2, 3, 2]. 40 | Explanation 2: 41 | The number of divisors of 8 : [1, 2, 4, 8], 9 : [1, 3, 9], 10 : [1, 2, 5, 10] 42 | So the count will be [4, 3, 4]. 43 | """ 44 | 45 | ## Solution 46 | 47 | class Solution: 48 | # @param A : list of integers 49 | # @return a list of integers 50 | def divisors_count(self, num): 51 | if num == 1: 52 | return 1 53 | count = 2 54 | for factor in range(2, int(num**0.5)+1): 55 | if num % factor == 0: 56 | if num//factor == factor: 57 | count += 1 58 | else: 59 | count += 2 60 | return count 61 | 62 | def solve(self, A): 63 | ans_arr = [] 64 | traversed = dict() 65 | for num in A: 66 | traversed[num] = traversed.get(num, self.divisors_count(num)) 67 | ans_arr.append(traversed[num]) 68 | return ans_arr 69 | 70 | ## Optimized Solution 71 | 72 | divisors_count = [2] * 1000001 73 | divisors_count[1] = 1 74 | 75 | i = 2 76 | while i <= 1000001: 77 | for factor in range(2*i, 1000001, i): 78 | divisors_count[factor] += 1 79 | i += 1 80 | 81 | class Solution: 82 | # @param A : list of integers 83 | # @return a list of integers 84 | 85 | def solve(self, A): 86 | A_length = len(A) 87 | ans_arr = [0] * A_length 88 | for index in range(A_length): 89 | ans_arr[index] = divisors_count[A[index]] 90 | return ans_arr 91 | 92 | -------------------------------------------------------------------------------- /InterviewBit/Day 8/Assignment/Factorial Array: -------------------------------------------------------------------------------- 1 | ## Question 2 | 3 | """ 4 | Factorial Array 5 | Problem Description 6 | Groot has an array A of size N. Boring right? Groot thought so too, so he decided to construct another array B of the same size and defined elements of B as: B[i] = factorial of A[i] for every i such that 1<= i <= N. 7 | factorial of a number X denotes (1 x 2 x 3 x 4......(X-1) x (X)). 8 | Now Groot is interested in the total number of non-empty subsequences of array B such that every element in the subsequence has the same non empty set of prime factors. Since the number can be very large, return it modulo 109 + 7. NOTE: A set is a data structure having only distinct elements. Eg : the set of prime factors of Y=12 will be {2,3} and not {2,2,3} 9 | 10 | 11 | Problem Constraints 12 | 1 <= N <= 105 13 | 1 <= A[i] <= 106 14 | Your code will run against a maximum of 5 test cases. 15 | 16 | 17 | Input Format 18 | Only argument is an integer array A of size N. 19 | 20 | 21 | Output Format 22 | Return an integer deonting the total number of non-empty subsequences of array B such that every element in the subsequence has the same set of prime factors modulo 109+7. 23 | 24 | 25 | Example Input 26 | Input 1: 27 | A = [2, 3, 2, 3] 28 | Input 2: 29 | A = [2, 3, 4] 30 | 31 | 32 | 33 | Example Output 34 | Output 1: 35 | 6 36 | Output 2: 37 | 4 38 | 39 | 40 | 41 | Example Explanation 42 | Explanation 1: 43 | Array B will be : [2, 6, 2, 6] 44 | The total possible subsequences are 6 : [2], [2], [2, 2], [6], [6], [6, 6]. 45 | Input 2: 46 | Array B will be : [2, 6, 24] 47 | The total possible subsequences are 4 : [2], [6], [24], [6, 24]. 48 | """ 49 | 50 | ## Solution 51 | 52 | class Solution: 53 | # @param A : list of integers 54 | # @return an integer 55 | nearest_small_prime = [True for i in range(1000001)] 56 | p = 2 57 | while p*p <= 1000001: 58 | if nearest_small_prime[p]: 59 | for i in range(2*p, 1000001, p): 60 | nearest_small_prime[i] = False 61 | p += 1 62 | nearest_small_prime[1] = 1 63 | nearest_small_prime[2] = 2 64 | nearest_small_prime[3] = 3 65 | previous_prime = 3 66 | for index in range(4,1000001): 67 | if nearest_small_prime[index]: 68 | nearest_small_prime[index] = index 69 | previous_prime = index 70 | else: 71 | nearest_small_prime[index] = previous_prime 72 | 73 | def solve(self, A): 74 | A_length = len(A) 75 | freq_dict = {} 76 | 77 | for index in range(A_length): 78 | if A[index] != 1: 79 | A[index] = self.nearest_small_prime[A[index]] 80 | freq_dict[A[index]] = freq_dict.get(A[index], 0) + 1 81 | 82 | sub_seq_count = 0 83 | 84 | for freq in freq_dict.values(): 85 | sub_seq_count += (2**freq) - 1 86 | 87 | return sub_seq_count 88 | 89 | -------------------------------------------------------------------------------- /InterviewBit/Day 8/Homework/Find nth Magic Number: -------------------------------------------------------------------------------- 1 | ## Question 2 | 3 | """ 4 | Find nth Magic Number 5 | Problem Description 6 | Given an integer A, find and return the A'th magic number. A magic number is defined as a number which can be expressed as a power of 5 or sum of unique powers of 5. First few magic numbers are 5, 25, 30(5 + 25), 125, 130(125 + 5), …. 7 | 8 | 9 | Problem Constraints 10 | 1 <= A <= 5000 11 | 12 | 13 | Input Format 14 | The only argument given is integer A. 15 | 16 | 17 | Output Format 18 | Return the Ath magic number. 19 | 20 | 21 | Example Input 22 | Example Input 1: 23 | A = 3 24 | Example Input 2: 25 | A = 10 26 | 27 | 28 | 29 | Example Output 30 | Example Output 1: 31 | 30 32 | Example Output 2: 33 | 650 34 | 35 | 36 | 37 | Example Explanation 38 | Explanation 1: 39 | A in increasing order is [5, 25, 30, 125, 130, ...] 40 | 3rd element in this is 30 41 | """ 42 | 43 | ## Solution 44 | 45 | class Solution: 46 | # @param A : integer 47 | # @return an integer 48 | def solve(self, A): 49 | binary = bin(A)[2:][::-1] 50 | magic_number = 0 51 | i = 1 52 | for ele in binary: 53 | if ele == "1": 54 | magic_number += 5**i 55 | i += 1 56 | return magic_number 57 | -------------------------------------------------------------------------------- /InterviewBit/Day 8/Homework/Lucky Numbers: -------------------------------------------------------------------------------- 1 | ## Question 2 | 3 | """" 4 | Lucky Numbers 5 | A lucky number is a number which has exactly 2 distinct prime divisors. You are given a number N and you need to determine the count of lucky numbers between the range 1 to N (both inclusive). Input 6 | The first argument contains one integer number N (1 ≤  N  ≤ 5000). 7 | Output 8 | Return an integer i.e the count of lucky numbers between 1 and N, both inclusive. 9 | Examples Input 10 | 8 11 | Output 12 | 1 13 | Explanation Testcase 1- 14 | Between [1,8] there is only 1 lucky number i.e 6 15 | """ 16 | 17 | ## Solution 18 | 19 | is_prime = [True]*5001 20 | p = 2 21 | while p*p <= 5001: 22 | if is_prime[p]: 23 | for num in range(2*p, 5001, p): 24 | is_prime[num] = False 25 | p += 1 26 | 27 | class Solution: 28 | # @param A : integer 29 | # @return an integer 30 | def divisors_count(self, num): 31 | count = 0 32 | temp = num 33 | for factor in range(2, num): 34 | if not temp%factor: 35 | while not temp%factor: 36 | temp //= factor 37 | count += 1 38 | if count == 2: 39 | return True 40 | return False 41 | 42 | def solve(self, A): 43 | lucky_num_count = 0 44 | for num in range(6, A+1): 45 | if not is_prime[num] and self.divisors_count(num): 46 | lucky_num_count += 1 47 | return lucky_num_count 48 | 49 | -------------------------------------------------------------------------------- /InterviewBit/Day 8/Homework/Prime Sum: -------------------------------------------------------------------------------- 1 | ## Question 2 | 3 | """ 4 | Prime Sum 5 | Problem Description 6 | Given an even number A ( greater than 2 ), return two prime numbers whose sum will be equal to given number. If there are more than one solutions possible, return the lexicographically smaller solution. 7 | If [a, b] is one solution with a <= b, and [c,d] is another solution with c <= d, then 8 | [a, b] < [c, d], If a < c OR a==c AND b < d. 9 | NOTE: A solution will always exist. Read Goldbach's conjecture. 10 | 11 | 12 | Problem Constraints 13 | 4 <= A <= 2*107 14 | 15 | 16 | Input Format 17 | First and only argument of input is an even number A. 18 | 19 | 20 | Output Format 21 | Return a integer array of size 2 containing primes whose sum will be equal to given number. 22 | 23 | 24 | Example Input 25 | 4 26 | 27 | 28 | Example Output 29 | [2, 2] 30 | 31 | 32 | Example Explanation 33 | There is only 1 solution for A = 4. 34 | """ 35 | 36 | ## Solution 37 | 38 | 39 | class Solution: 40 | # @param A : integer 41 | # @return a list of integers 42 | def is_prime(self, num): 43 | for factor in range(2, int(num ** 0.5)+1): 44 | if not num%factor: 45 | return False 46 | return True 47 | 48 | def primesum(self, A): 49 | for num in range(2,A+1): 50 | if self.is_prime(num) and self.is_prime(A-num): 51 | return [num, A-num] 52 | -------------------------------------------------------------------------------- /InterviewBit/Day-3/HomeWork/Alternate positive and negative elements (Using Extra Space): -------------------------------------------------------------------------------- 1 | def solve(self, A): 2 | pos_ele_count = 0 3 | neg_ele_count = 0 4 | pos = [] 5 | neg = [] 6 | for ele in A: 7 | if ele < 0: 8 | neg.append(ele) 9 | neg_ele_count += 1 10 | else: 11 | pos.append(ele) 12 | pos_ele_count += 1 13 | ans = [0]*(pos_ele_count+neg_ele_count) 14 | ans_index = 0 15 | pos_index = 0 16 | neg_index = 0 17 | while pos_index < pos_ele_count and neg_index < neg_ele_count: 18 | ans[ans_index] = neg[neg_index] 19 | ans_index += 1 20 | neg_index += 1 21 | ans[ans_index] = pos[pos_index] 22 | ans_index += 1 23 | pos_index += 1 24 | if ans[ans_index] < 0: 25 | while pos_index < pos_ele_count: 26 | ans[ans_index] = pos[pos_index] 27 | ans_index += 1 28 | pos_index += 1 29 | while neg_index < neg_ele_count: 30 | ans[ans_index] = neg[neg_index] 31 | ans_index += 1 32 | neg_index += 1 33 | else: 34 | while neg_index < neg_ele_count: 35 | ans[ans_index] = neg[neg_index] 36 | ans_index += 1 37 | neg_index += 1 38 | while pos_index < pos_ele_count: 39 | ans[ans_index] = pos[pos_index] 40 | ans_index += 1 41 | pos_index += 1 42 | return ans 43 | 44 | -------------------------------------------------------------------------------- /LeetCode/Easy/Binary Search.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/binary-search/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | class Solution: 10 | def search(self, nums: List[int], target: int) -> int: 11 | nums_len = len(nums) 12 | start = 0 13 | end = nums_len -1 14 | 15 | while start <= end: 16 | mid = (start+end)//2 17 | if nums[mid] < target: 18 | start = mid + 1 19 | 20 | elif nums[mid] > target: 21 | end = end - 1 22 | else: 23 | return mid 24 | 25 | return -1 26 | ``` 27 | 28 | # Code Explanation 29 | -------------------------------------------------------------------------------- /LeetCode/Easy/Binary Tree Tilt.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/binary-tree-tilt/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | # Definition for a binary tree node. 10 | # class TreeNode: 11 | # def __init__(self, val=0, left=None, right=None): 12 | # self.val = val 13 | # self.left = left 14 | # self.right = right 15 | 16 | class Solution: 17 | 18 | def post_order(self, node: TreeNode) -> None: 19 | if not node: return None 20 | 21 | self.post_order(node.left) 22 | self.post_order(node.right) 23 | 24 | left_tree_sum = node.left.sum if node.left else 0 25 | right_tree_sum = node.right.sum if node.right else 0 26 | 27 | node.sum = left_tree_sum + right_tree_sum + node.val 28 | self.tilt_val += abs(left_tree_sum - right_tree_sum) 29 | 30 | 31 | def findTilt(self, root: TreeNode) -> int: 32 | self.tilt_val = 0 33 | self.post_order(root) 34 | 35 | return self.tilt_val 36 | 37 | ``` 38 | 39 | # Code Explanation 40 | -------------------------------------------------------------------------------- /LeetCode/Easy/Buddy Strings.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/buddy-strings/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | class Solution: 10 | def buddyStrings(self, A: str, B: str) -> bool: 11 | mismatch = 0 12 | A_len = len(A) 13 | B_len = len(B) 14 | 15 | if A_len != B_len: 16 | return False 17 | 18 | diff = [] 19 | for index in range(A_len): 20 | if A[index] != B[index]: 21 | mismatch += 1 22 | diff.append((A[index],B[index])) 23 | if mismatch == 3: 24 | return False 25 | 26 | if mismatch == 2: 27 | a1, b1 = diff[0] 28 | a2, b2 = diff[1] 29 | if a1 == b2 and a2 == b1: 30 | return True 31 | else: 32 | return False 33 | 34 | if mismatch == 0: 35 | freq = {} 36 | for char in A: 37 | freq[char] = freq.get(char, 0) + 1 38 | if freq[char] == 2: 39 | return True 40 | return False 41 | 42 | return False 43 | ``` 44 | 45 | # Code Explanation 46 | -------------------------------------------------------------------------------- /LeetCode/Easy/Complement of Base 10 Integer.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/complement-of-base-10-integer/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | class Solution: 10 | def bitwiseComplement(self, N): 11 | 12 | if N == 0: 13 | return 1 14 | 15 | # Getting binary complement of N 16 | 17 | comp_num = 0 18 | power_val = 0 19 | 20 | while N > 0: 21 | rem = N%2 22 | if rem == 0: 23 | comp_num += 2**(power_val) 24 | 25 | power_val += 1 26 | N = N//2 27 | 28 | return comp_num 29 | ``` 30 | 31 | # Code Explanation 32 | -------------------------------------------------------------------------------- /LeetCode/Easy/Consecutive Characters.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/consecutive-characters/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | class Solution: 10 | def maxPower(self, s: str) -> int: 11 | max_power = power = 1 12 | s_len = len(s) 13 | 14 | for index in range(1, s_len): 15 | if s[index] == s[index-1]: 16 | power += 1 17 | else: 18 | max_power = max(max_power, power) 19 | power = 1 20 | 21 | return max(max_power, power) 22 | ``` 23 | 24 | # Code Explanation 25 | -------------------------------------------------------------------------------- /LeetCode/Easy/Convert Binary Number in a Linked List to Integer.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/ 3 | 4 | # Approach 5 | 6 | - Traverse the link list from left to right 7 | - While traversing store values of node into a concatenated string 8 | - Multiply the string value with 2index 9 | - Store the accumalted sum in a decimal variable 10 | 11 | # Python Code 12 | 13 | ```Python 14 | # Definition for singly-linked list. 15 | # class ListNode: 16 | # def __init__(self, val=0, next=None): 17 | # self.val = val 18 | # self.next = next 19 | 20 | class Solution: 21 | def getDecimalValue(self, head: ListNode) -> int: 22 | binary_str = "" 23 | binary_len = 0 24 | curr = head 25 | 26 | while curr: 27 | binary_str = str(curr.val) + binary_str 28 | binary_len += 1 29 | curr = curr.next 30 | 31 | decimal_val = 0 32 | for index in range(binary_len): 33 | if binary_str[index] == '1': 34 | decimal_val += 2**(index) 35 | 36 | return decimal_val 37 | ``` 38 | 39 | # Code Explanation 40 | -------------------------------------------------------------------------------- /LeetCode/Easy/Find the Difference.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/find-the-difference/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | from collections import Counter 10 | from string import ascii_lowercase 11 | 12 | class Solution: 13 | def findTheDifference(self, s: str, t: str) -> str: 14 | s_freq = Counter(s) 15 | t_freq = Counter(t) 16 | for char in ascii_lowercase: 17 | if s_freq[char] != t_freq[char]: 18 | return char 19 | ``` 20 | 21 | # Code Explanation 22 | 23 | -------------------------------------------------------------------------------- /LeetCode/Easy/Flipping an Image.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/flipping-an-image/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | class Solution: 10 | def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]: 11 | for index, row in enumerate(A): 12 | A[index] = [0 if pixel else 1 for pixel in row[::-1]] 13 | return A 14 | 15 | ``` 16 | 17 | # Code Explanation 18 | -------------------------------------------------------------------------------- /LeetCode/Easy/Minimum Cost to Move Chips to The Same Position.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | from collections import defaultdict 10 | 11 | class Solution: 12 | def minCostToMoveChips(self, position: List[int]) -> int: 13 | chips_at_position = defaultdict(int) 14 | for chip_position in position: 15 | chips_at_position[chip_position] += 1 16 | 17 | chips_at_odd = chips_at_even = 0 18 | for chip_position, chip_count in chips_at_position.items(): 19 | if chip_position % 2: 20 | chips_at_odd += chip_count 21 | else: 22 | chips_at_even += chip_count 23 | 24 | return min(chips_at_odd, chips_at_even) 25 | ``` 26 | 27 | # Code Explanation 28 | -------------------------------------------------------------------------------- /LeetCode/Easy/Minimum Depth of Binary Tree.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/minimum-depth-of-binary-tree/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | # Definition for a binary tree node. 10 | # class TreeNode: 11 | # def __init__(self, val=0, left=None, right=None): 12 | # self.val = val 13 | # self.left = left 14 | # self.right = right 15 | 16 | from collections import deque 17 | 18 | class Solution: 19 | 20 | def is_leaf(self, node): 21 | return not node.left and not node.right 22 | 23 | def minDepth(self, root: TreeNode) -> int: 24 | if not root: return 0 25 | 26 | if self.is_leaf(root): return 1 27 | 28 | queue = deque([(root,1)]) 29 | while queue: 30 | curr, count = queue.popleft() 31 | if self.is_leaf(curr): 32 | return count 33 | 34 | if curr.left: 35 | queue.append((curr.left, count+1)) 36 | 37 | if curr.right: 38 | queue.append((curr.right, count+1)) 39 | 40 | #return min_depth 41 | 42 | 43 | 44 | ``` 45 | 46 | # Code Explanation 47 | -------------------------------------------------------------------------------- /LeetCode/Easy/Number of Recent Calls.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/number-of-recent-calls/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | class RecentCounter: 10 | 11 | def __init__(self): 12 | self.ping_time = [] 13 | 14 | 15 | def ping(self, t: int) -> int: 16 | self.ping_time.append(t) 17 | first_ping = t-3000 18 | count = 0 19 | for curr_ping in self.ping_time[::-1]: 20 | if curr_ping >= first_ping: 21 | count += 1 22 | else: 23 | break 24 | return count 25 | 26 | 27 | # Your RecentCounter object will be instantiated and called as such: 28 | # obj = RecentCounter() 29 | # param_1 = obj.ping(t) 30 | 31 | ``` 32 | 33 | # Code Explanation 34 | -------------------------------------------------------------------------------- /LeetCode/Easy/Summary Ranges.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/summary-ranges/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | class Solution: 10 | def summaryRanges(self, nums: List[int]) -> List[str]: 11 | if not nums: return [] 12 | ranges = [] 13 | nums_len = len(nums) 14 | start = nums[0] 15 | end = nums[0] 16 | for index in range(1,nums_len): 17 | if nums[index] == nums[index-1]+1: 18 | end = nums[index] 19 | else: 20 | if start < end: 21 | ranges += [str(start)+'->'+str(end)] 22 | else: 23 | ranges += [str(start)] 24 | start = nums[index] 25 | 26 | if start < end: 27 | ranges += [str(start)+'->'+str(end)] 28 | else: 29 | ranges += [str(start)] 30 | 31 | return ranges 32 | ``` 33 | 34 | # Code Explanation 35 | -------------------------------------------------------------------------------- /LeetCode/Hard/Best Time to Buy and Sell Stock IV.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | class Solution: 10 | def maxProfit(self, k: int, prices: List[int]) -> int: 11 | prices_len = len(prices) 12 | if prices_len <= 1 or k == 0: return 0 13 | 14 | if k >= prices_len//2: 15 | profit = 0 16 | for index in range(1, prices_len): 17 | if prices[index] > prices[index-1]: 18 | profit += prices[index]-prices[index-1] 19 | return profit 20 | 21 | MIN_VAL = -float('inf') 22 | buy = [MIN_VAL] * k 23 | sell = [0] * k 24 | 25 | for price in prices: 26 | for day in range(k): 27 | buy[day] = max(buy[day], sell[day-1]-price if day != 0 else -price) 28 | sell[day] = max(sell[day], buy[day]+price) 29 | 30 | return sell[k-1] 31 | 32 | ``` 33 | 34 | # Code Explanation 35 | -------------------------------------------------------------------------------- /LeetCode/Hard/First Missing Positive.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/first-missing-positive/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | class Solution: 10 | def firstMissingPositive(self, nums: List[int]) -> int: 11 | nums_len = len(nums) 12 | 13 | for _ in range(4): 14 | 15 | for index in range(nums_len): 16 | curr_ele = nums[index] 17 | if index+1 != curr_ele and 0 < curr_ele < nums_len: 18 | nums[index], nums[curr_ele-1] = nums[curr_ele-1], nums[index] 19 | 20 | 21 | for index in range(nums_len-1, -1, -1): 22 | curr_ele = nums[index] 23 | if index+1 != curr_ele and 0 < curr_ele < nums_len: 24 | nums[index], nums[curr_ele-1] = nums[curr_ele-1], nums[index] 25 | 26 | print(nums) 27 | 28 | for index in range(nums_len): 29 | if index+1 != nums[index]: 30 | return index+1 31 | 32 | return nums_len+1 33 | 34 | ``` 35 | 36 | # Code Explanation 37 | -------------------------------------------------------------------------------- /LeetCode/Hard/Recover Binary Search Tree.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/recover-binary-search-tree/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | # Definition for a binary tree node. 10 | # class TreeNode: 11 | # def __init__(self, val=0, left=None, right=None): 12 | # self.val = val 13 | # self.left = left 14 | # self.right = right 15 | 16 | class Solution: 17 | def recoverTree(self, root: TreeNode) -> None: 18 | """ 19 | Do not return anything, modify root in-place instead. 20 | """ 21 | tree = [] 22 | 23 | def inorder(root, tree): 24 | if not root: return [] 25 | inorder(root.left, tree) 26 | tree += [root] 27 | inorder(root.right, tree) 28 | 29 | inorder(root, tree) 30 | 31 | bst = sorted(tree, key = lambda x:x.val) 32 | 33 | node1 = node2 = None 34 | 35 | for index in range(len(tree)): 36 | if tree[index].val != bst[index].val: 37 | tree[index].val, bst[index].val = bst[index].val, tree[index].val 38 | break 39 | ``` 40 | 41 | # Code Explanation 42 | -------------------------------------------------------------------------------- /LeetCode/Hard/Stone Game IV.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/stone-game-iv/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | """ 10 | class Solution: 11 | def winnerSquareGame(self, n: int) -> bool: 12 | win = [False] * (n+1) 13 | 14 | for index in range(1, n+1): 15 | for square in range(1, int(index**0.5)+1): 16 | if win[index-square**2] == False: 17 | win[index] = True 18 | 19 | return win[n] 20 | 21 | ``` 22 | 23 | # Code Explanation 24 | -------------------------------------------------------------------------------- /LeetCode/Hard/Unique Paths III.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/unique-paths-iii/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | neighbours = [(0,-1), (0, 1), (-1,0), (1, 0)] 10 | 11 | class Solution: 12 | 13 | def get_unique_paths_count(self, grid, row, col, zeros_count): 14 | if row < 0 or col < 0: 15 | return 16 | 17 | if row >= self.total_rows or col >= self.total_cols: 18 | return 19 | 20 | if grid[row][col] == 2: 21 | if zeros_count == self.total_zeros: 22 | self.unique_paths_count += 1 23 | return 24 | 25 | elif grid[row][col] == 0: 26 | 27 | grid[row][col] = -1 28 | 29 | for x,y in neighbours: 30 | self.get_unique_paths_count(grid, row+x, col+y, zeros_count+1) 31 | 32 | grid[row][col] = 0 33 | 34 | return 35 | 36 | def uniquePathsIII(self, grid: List[List[int]]) -> int: 37 | self.unique_paths_count = 0 38 | 39 | self.total_rows = len(grid) 40 | self.total_cols = len(grid[0]) 41 | 42 | start_row = start_col = 0 43 | self.total_zeros = 0 44 | 45 | for row in range(self.total_rows): 46 | for col in range(self.total_cols): 47 | if grid[row][col] == 0: 48 | self.total_zeros += 1 49 | elif grid[row][col] == 1: 50 | start_row = row 51 | start_col = col 52 | 53 | grid[start_row][start_col] = -1 54 | for x, y in neighbours: 55 | self.get_unique_paths_count(grid, start_row+x, start_col+y, 0) 56 | 57 | return self.unique_paths_count 58 | ``` 59 | 60 | # Code Explanation 61 | -------------------------------------------------------------------------------- /LeetCode/Medium/132 Pattern.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/132-pattern/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ## Time Complexity : O(N^3) 9 | 10 | ```Python 11 | class Solution: 12 | def find_i(self, curr_index, curr_num): 13 | for index in range(curr_index): 14 | if self.nums[index] < curr_num: 15 | return index 16 | 17 | def find_j(self, start, end, curr_num): 18 | for index in range(start, end): 19 | if self.nums[index] > curr_num: 20 | return index 21 | 22 | def find132pattern(self, nums: List[int]) -> bool: 23 | self.nums = nums 24 | nums_len = len(self.nums) 25 | for index in range(2, nums_len): 26 | curr_num = nums[index] 27 | print(curr_num) 28 | i_index = self.find_i(index, curr_num) 29 | if i_index != None: 30 | if self.find_j(i_index, index, curr_num) != None: 31 | return True 32 | 33 | return False 34 | ``` 35 | 36 | ## Code Explanation 37 | 38 | ## Time Complexity : 39 | 40 | ```Python 41 | 42 | 43 | ``` 44 | 45 | ## Code Explanation 46 | -------------------------------------------------------------------------------- /LeetCode/Medium/Add Two Numbers II.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/add-two-numbers-ii/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | """ 10 | # Definition for singly-linked list. 11 | # class ListNode: 12 | # def __init__(self, val=0, next=None): 13 | # self.val = val 14 | # self.next = next 15 | 16 | class Solution: 17 | def get_values(self, node): 18 | stack = [] 19 | if not node: return [0] 20 | while node: 21 | stack += [node.val] 22 | node = node.next 23 | return stack 24 | 25 | def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: 26 | stack1 = self.get_values(l1) 27 | stack2 = self.get_values(l2) 28 | carry = 0 29 | prev_node = None 30 | 31 | while stack1 or stack2: 32 | val1 = stack1.pop() if stack1 else 0 33 | val2 = stack2.pop() if stack2 else 0 34 | total_val = val1 + val2 + carry 35 | if total_val > 9: 36 | digit = total_val % 10 37 | carry = 1 38 | else: 39 | digit = total_val 40 | carry = 0 41 | 42 | curr_node = ListNode(digit) 43 | if prev_node: 44 | curr_node.next = prev_node 45 | 46 | prev_node = curr_node 47 | 48 | if carry: 49 | curr_node = ListNode(carry) 50 | curr_node.next = prev_node 51 | 52 | return curr_node 53 | 54 | ``` 55 | 56 | # Code Explanation 57 | -------------------------------------------------------------------------------- /LeetCode/Medium/Asteroid Collision.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/asteroid-collision/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | """ 10 | class Solution: 11 | 12 | def asteroidCollision(self, asteroids: List[int]) -> List[int]: 13 | ans = [asteroids[0]] 14 | for asteroid in asteroids[1:]: 15 | if asteroid > 0: 16 | ans.append(asteroid) 17 | else: 18 | while ans and ans[-1] > 0: 19 | if abs(ans[-1]) < abs(asteroid): 20 | ans.pop() 21 | else: 22 | break 23 | if ans: 24 | if ans[-1] < 0: 25 | ans.append(asteroid) 26 | else: 27 | if abs(ans[-1]) == abs(asteroid): 28 | ans.pop() 29 | else: 30 | ans.append(asteroid) 31 | return ans 32 | ``` 33 | 34 | # Code Explanation 35 | -------------------------------------------------------------------------------- /LeetCode/Medium/Bag of Tokens.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/bag-of-tokens/submissions/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | """ 10 | class Solution: 11 | def bagOfTokensScore(self, tokens: List[int], P: int) -> int: 12 | if not tokens or not P: return 0 13 | tokens.sort() 14 | score = 0 15 | power = P 16 | start = 0 17 | end = len(tokens)-1 18 | 19 | while start < end: 20 | if tokens[start] <= power: 21 | power -= tokens[start] 22 | score += 1 23 | start += 1 24 | else: 25 | if not score: return 0 26 | score -= 1 27 | power += tokens[end] 28 | end -= 1 29 | 30 | if power >= tokens[start]: 31 | score += 1 32 | power -= tokens[start] 33 | 34 | return score 35 | 36 | ``` 37 | 38 | # Code Explanation 39 | -------------------------------------------------------------------------------- /LeetCode/Medium/Car Pooling.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/car-pooling/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | 10 | class Solution: 11 | def carPooling(self, trips: List[List[int]], capacity: int) -> bool: 12 | trips_length = len(trips) 13 | 14 | if trips_length == 0: 15 | return True 16 | 17 | location = [0] * 1001 18 | 19 | for passengers, start, end in trips: 20 | 21 | for index in range(start, end): 22 | location[index] += passengers 23 | if location[index] > capacity: 24 | return False 25 | 26 | return True 27 | ``` 28 | 29 | # Code Explanation 30 | -------------------------------------------------------------------------------- /LeetCode/Medium/Champagne Tower.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/champagne-tower/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | """ 10 | class Solution: 11 | def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float: 12 | 13 | glass = [poured] 14 | 15 | for row in range(query_row): 16 | temp_glass = [0] * (len(glass)+1) 17 | for index in range(len(glass)): 18 | pour = (glass[index]-1)/2 19 | if pour > 0: 20 | temp_glass[index] += pour 21 | temp_glass[index+1] += pour 22 | glass = temp_glass 23 | 24 | return min(1, glass[query_glass]) 25 | 26 | ``` 27 | 28 | # Code Explanation 29 | -------------------------------------------------------------------------------- /LeetCode/Medium/Clone Graph.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/clone-graph/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | """ 10 | # Definition for a Node. 11 | class Node: 12 | def __init__(self, val = 0, neighbors = None): 13 | self.val = val 14 | self.neighbors = neighbors if neighbors is not None else [] 15 | """ 16 | 17 | from collections import deque 18 | 19 | class Solution: 20 | def cloneGraph(self, node: 'Node') -> 'Node': 21 | if not node: return None 22 | 23 | hash_map = {node:Node(node.val)} 24 | 25 | queue = deque([node]) 26 | traversed = set([node]) 27 | 28 | while queue: 29 | curr = queue.popleft() 30 | parent = hash_map.get(curr) 31 | for neighbor in curr.neighbors: 32 | hash_map[neighbor] = hash_map.get(neighbor, Node(neighbor.val)) 33 | child = hash_map[neighbor] 34 | parent.neighbors.append(child) 35 | if neighbor not in traversed: 36 | queue.append(neighbor) 37 | traversed.add(neighbor) 38 | 39 | return hash_map[node] 40 | ``` 41 | 42 | # Code Explanation 43 | -------------------------------------------------------------------------------- /LeetCode/Medium/Combination Sum.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/combination-sum/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | class Solution: 10 | def get_combinations(self, candidates, target, index, combination, curr_sum): 11 | if curr_sum > target or index == self.total_candidates: 12 | return 13 | 14 | if curr_sum == target: 15 | self.all_combinations.add(tuple(combination)) 16 | return 17 | 18 | comb_copy = combination[:] 19 | 20 | self.get_combinations(candidates, target, index, comb_copy+[candidates[index]], 21 | curr_sum+candidates[index]) 22 | 23 | self.get_combinations(candidates, target, index+1, comb_copy+[candidates[index]], 24 | curr_sum+candidates[index]) 25 | 26 | self.get_combinations(candidates, target, index+1, comb_copy, curr_sum) 27 | 28 | 29 | def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: 30 | self.total_candidates = len(candidates) 31 | self.all_combinations = set() 32 | self.get_combinations(candidates, target, 0, [], 0) 33 | 34 | return self.all_combinations 35 | ``` 36 | 37 | # Code Explanation 38 | -------------------------------------------------------------------------------- /LeetCode/Medium/Evaluate Division.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/evaluate-division/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | from collections import deque 10 | 11 | class Solution: 12 | def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: 13 | graph = defaultdict(dict) 14 | 15 | equations_len = len(equations) 16 | 17 | for index in range(equations_len): 18 | source, dest = equations[index] 19 | weight = values[index] 20 | 21 | graph[source][dest] = weight 22 | graph[dest][source] = 1/weight 23 | 24 | 25 | ans = [] 26 | 27 | for src, dest in queries: 28 | 29 | if src not in graph or dest not in graph: 30 | ans.append(-1) 31 | 32 | elif src == dest : 33 | ans.append(1) 34 | 35 | else: 36 | queue = deque([(src,1.0)]) 37 | visited = set([src]) 38 | dest_found = False 39 | while queue: 40 | node, weight = queue.popleft() 41 | for child in graph[node]: 42 | new_weight = weight * graph[node][child] 43 | if child == dest: 44 | ans.append(new_weight) 45 | dest_found = True 46 | break 47 | 48 | if child not in visited: 49 | visited.add(child) 50 | queue.append((child, new_weight)) 51 | 52 | if dest_found: 53 | break 54 | 55 | if not dest_found: 56 | ans.append(-1) 57 | 58 | return ans 59 | ``` 60 | 61 | # Code Explanation 62 | -------------------------------------------------------------------------------- /LeetCode/Medium/Gas Station.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/gas-station/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | class Solution: 10 | def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: 11 | if sum(gas)-sum(cost) < 0: 12 | return -1 13 | 14 | total_stations = len(gas) 15 | 16 | first_station = 0 17 | current_gas = 0 18 | 19 | for index in range(total_stations): 20 | current_gas += gas[index]-cost[index] 21 | if current_gas < 0: 22 | first_station = index+1 23 | current_gas = 0 24 | 25 | return first_station 26 | ``` 27 | 28 | # Code Explanation 29 | -------------------------------------------------------------------------------- /LeetCode/Medium/House Robber II.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/house-robber-ii/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | class Solution: 10 | def rob(self, nums: List[int]) -> int: 11 | nums_len = len(nums) 12 | 13 | if nums_len < 2: return max(nums) 14 | 15 | money = [0] * nums_len 16 | money[0] = nums[0] 17 | money[1] = max(nums[0], nums[1]) 18 | 19 | for index in range(2, nums_len-1): 20 | money[index] = max(nums[index]+money[index-2], money[index-1]) 21 | 22 | ans1 = money[-2] 23 | 24 | money = [0] * nums_len 25 | money[1] = nums[1] 26 | for index in range(2, nums_len): 27 | money[index] = max(nums[index]+money[index-2], money[index-1]) 28 | 29 | ans2 = money[-1] 30 | 31 | return max(ans1, ans2) 32 | ``` 33 | 34 | # Code Explanation 35 | -------------------------------------------------------------------------------- /LeetCode/Medium/Insert into a Binary Search Tree.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/insert-into-a-binary-search-tree/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | # Definition for a binary tree node. 10 | # class TreeNode: 11 | # def __init__(self, val=0, left=None, right=None): 12 | # self.val = val 13 | # self.left = left 14 | # self.right = right 15 | 16 | class Solution: 17 | def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode: 18 | curr = root 19 | 20 | while curr: 21 | if val > curr.val: 22 | if curr.right: 23 | curr = curr.right 24 | else: 25 | curr.right = TreeNode(val) 26 | break 27 | else: 28 | if curr.left: 29 | curr = curr.left 30 | else: 31 | curr.left = TreeNode(val) 32 | break 33 | 34 | return root if root else TreeNode(val) 35 | 36 | ``` 37 | 38 | # Code Explanation 39 | -------------------------------------------------------------------------------- /LeetCode/Medium/Insertion Sort List.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/insertion-sort-list/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | """ 10 | # Definition for singly-linked list. 11 | # class ListNode: 12 | # def __init__(self, val=0, next=None): 13 | # self.val = val 14 | # self.next = next 15 | 16 | class Solution: 17 | def insertionSortList(self, head: ListNode) -> ListNode: 18 | 19 | i_ptr = head 20 | while i_ptr: 21 | j_ptr = i_ptr.next 22 | temp = i_ptr 23 | while j_ptr: 24 | if j_ptr.val < temp.val: 25 | temp = j_ptr 26 | j_ptr = j_ptr.next 27 | i_ptr.val, temp.val = temp.val, i_ptr.val 28 | i_ptr = i_ptr.next 29 | 30 | return head 31 | ``` 32 | 33 | # Code Explanation 34 | -------------------------------------------------------------------------------- /LeetCode/Medium/K-diff Pairs in an Array.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/k-diff-pairs-in-an-array/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | class Solution: 10 | def pair_exist(self, nums: List[int], start: int, end: int, target: int) -> bool: 11 | while start <= end: 12 | mid = (start+end)//2 13 | if nums[mid] > target: 14 | end = mid-1 15 | elif nums[mid] < target: 16 | start = mid + 1 17 | else: 18 | return True 19 | return False 20 | 21 | def findPairs(self, nums: List[int], k: int) -> int: 22 | nums.sort() 23 | nums_len = len(nums) 24 | 25 | pairs_count = int(self.pair_exist(nums, 1, nums_len-1, nums[0]+k)) 26 | 27 | for index in range(1,nums_len): 28 | if nums[index] != nums[index-1]: 29 | target = nums[index]+k 30 | if self.pair_exist(nums, index+1, nums_len-1, target): 31 | pairs_count += 1 32 | 33 | return pairs_count 34 | ``` 35 | 36 | # Code Explanation 37 | -------------------------------------------------------------------------------- /LeetCode/Medium/Largest Number.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/largest-number/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ## Time Complexity : O(N^2) 9 | 10 | ```Python 11 | 12 | class Solution: 13 | def check_swap(self, str_nums, i, j): 14 | without_swap = str_nums[i] + str_nums[j] 15 | with_swap = str_nums[j] + str_nums[i] 16 | if with_swap > without_swap: 17 | return True 18 | return False 19 | 20 | def largestNumber(self, nums: List[int]) -> str: 21 | total_nums = len(nums) 22 | str_nums = list(map(str, nums)) 23 | 24 | for i in range(total_nums): 25 | for j in range(i+1, total_nums): 26 | if self.check_swap(str_nums, i, j): 27 | str_nums[i], str_nums[j] = str_nums[j], str_nums[i] 28 | 29 | new_str = "".join(str_nums) 30 | if set(new_str) == {'0'}: 31 | return '0' 32 | 33 | return new_str 34 | 35 | ``` 36 | 37 | ## Code Explanation 38 | 39 | ## Time Complexity : O(NlogN) 40 | 41 | ```Python 42 | 43 | from functools import cmp_to_key 44 | 45 | class Solution: 46 | def largestNumber(self, nums: List[int]) -> str: 47 | str_nums = list(map(str, nums)) 48 | 49 | def compare(str1, str2): 50 | if str1+str2 < str2+str1: 51 | return 1 52 | return -1 53 | 54 | sorted_str = sorted(str_nums, key=cmp_to_key(compare)) 55 | 56 | if sorted_str[0] == '0': 57 | return '0' 58 | 59 | return "".join(sorted_str) 60 | 61 | ``` 62 | 63 | ## Code Explanation 64 | -------------------------------------------------------------------------------- /LeetCode/Medium/Linked List Cycle II.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/linked-list-cycle-ii/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | """ 10 | # Definition for singly-linked list. 11 | # class ListNode: 12 | # def __init__(self, x): 13 | # self.val = x 14 | # self.next = None 15 | """ 16 | 17 | class Solution: 18 | def detectCycle(self, head: ListNode) -> ListNode: 19 | curr = head 20 | while curr and curr.val != '*': 21 | curr.val = '*' 22 | curr = curr.next 23 | 24 | if not curr or curr.val != '*': return None 25 | 26 | return curr 27 | 28 | 29 | ``` 30 | 31 | # Code Explanation 32 | -------------------------------------------------------------------------------- /LeetCode/Medium/Majority Element II.md: -------------------------------------------------------------------------------- 1 | Question Link : https://leetcode.com/problems/majority-element-ii/ 2 | 3 | Approach : 4 | 5 | Solution: 6 | 7 | ```Python 8 | class Solution: 9 | def majorityElement(self, nums: List[int]) -> List[int]: 10 | 11 | total_nums = len(nums) 12 | 13 | if total_nums == 0: 14 | return [] 15 | 16 | first_ele = second_ele = None 17 | first_ele_count = second_ele_count = 0 18 | 19 | for num in nums: 20 | if num == first_ele: 21 | first_ele_count += 1 22 | elif num == second_ele: 23 | second_ele_count += 1 24 | elif first_ele_count == 0: 25 | first_ele = num 26 | first_ele_count += 1 27 | elif second_ele_count == 0: 28 | second_ele = num 29 | second_ele_count += 1 30 | else: 31 | first_ele_count -= 1 32 | second_ele_count -= 1 33 | 34 | major_eles = [] 35 | 36 | for ele in [first_ele, second_ele]: 37 | if nums.count(ele) > total_nums // 3: 38 | major_eles.append(ele) 39 | 40 | return major_eles 41 | ``` 42 | -------------------------------------------------------------------------------- /LeetCode/Medium/Maximize Distance to Closest Person.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/maximize-distance-to-closest-person/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ## Time Complexity : 9 | 10 | ```Python 11 | class Solution: 12 | def maxDistToClosest(self, seats: List[int]) -> int: 13 | total_seats = len(seats) 14 | seat_indices = [] 15 | occupied_seats = 0 16 | for seat_index in range(total_seats): 17 | if seats[seat_index]: 18 | seat_indices += [seat_index] 19 | occupied_seats += 1 20 | 21 | max_distance = max(1,seat_indices[0]) 22 | 23 | for index in range(occupied_seats-1): 24 | curr_distance = (seat_indices[index+1] - seat_indices[index])//2 25 | if curr_distance > max_distance: 26 | max_distance = curr_distance 27 | 28 | max_distance = max(max_distance, (total_seats-1)-seat_indices[-1] ) 29 | 30 | return max_distance 31 | ``` 32 | 33 | ## Code Explanation 34 | -------------------------------------------------------------------------------- /LeetCode/Medium/Maximum Difference Between Node and Ancestor.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | # Definition for a binary tree node. 10 | # class TreeNode: 11 | # def __init__(self, val=0, left=None, right=None): 12 | # self.val = val 13 | # self.left = left 14 | # self.right = right 15 | 16 | class Solution: 17 | def maxAncestorDiff(self, root: TreeNode) -> int: 18 | max_diff = float('-inf') 19 | visited = set() 20 | stack = [root] 21 | 22 | while stack: 23 | node = stack[-1] 24 | left_node = node.left 25 | right_node = node.right 26 | 27 | if left_node and left_node not in visited: 28 | stack.append(left_node) 29 | 30 | elif right_node and right_node not in visited: 31 | stack.append(right_node) 32 | 33 | else: 34 | if not left_node and not right_node: 35 | min_node = min(stack, key = lambda x:x.val) 36 | max_node = max(stack, key = lambda x:x.val) 37 | max_diff = max(max_diff, abs(max_node.val-min_node.val)) 38 | 39 | top = stack.pop() 40 | visited.add(top) 41 | 42 | return max_diff 43 | 44 | ``` 45 | 46 | # Code Explanation 47 | -------------------------------------------------------------------------------- /LeetCode/Medium/Minimum Domino Rotations For Equal Row.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | class Solution: 10 | 11 | def minDominoRotations(self, A: List[int], B: List[int]) -> int: 12 | total_dominos = len(A) 13 | 14 | A_freq = {} 15 | B_freq = {} 16 | AB_freq = {} 17 | for index in range(total_dominos): 18 | A_freq[A[index]] = A_freq.get(A[index], 0) + 1 19 | B_freq[B[index]] = B_freq.get(B[index], 0) + 1 20 | if A[index] != B[index]: 21 | AB_freq[A[index]] = AB_freq.get(A[index], 0) + 1 22 | AB_freq[B[index]] = AB_freq.get(B[index], 0) + 1 23 | else: 24 | AB_freq[A[index]] = AB_freq.get(A[index], 0) + 1 25 | 26 | swap_possible = False 27 | for val, freq in AB_freq.items(): 28 | if freq >= total_dominos: 29 | swap_possible = True 30 | break 31 | 32 | if not swap_possible: return -1 33 | 34 | A_min_swap = float('inf') 35 | B_min_swap = float('inf') 36 | for val, freq in AB_freq.items(): 37 | if AB_freq[val] == total_dominos: 38 | A_min_swap = min(A_freq[val], total_dominos-A_freq[val]) 39 | B_min_swap = min(B_freq[val], total_dominos-B_freq[val]) 40 | 41 | return min(A_min_swap, B_min_swap) 42 | ``` 43 | 44 | # Code Explanation 45 | -------------------------------------------------------------------------------- /LeetCode/Medium/Minimum Height Trees.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/minimum-height-trees/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | from collections import defaultdict, deque 10 | 11 | class Graph: 12 | def __init__(self, total_vertices, edges): 13 | self.total_vertices = total_vertices 14 | self.edges = edges 15 | self.create_graph() 16 | 17 | def create_graph(self): 18 | self.degree = defaultdict(int) 19 | self.graph = defaultdict(list) 20 | 21 | for parent, child in self.edges: 22 | self.graph[parent].append(child) 23 | self.graph[child].append(parent) 24 | 25 | self.degree[parent] += 1 26 | self.degree[child] += 1 27 | 28 | def get_min_height_nodes(self): 29 | queue = deque() 30 | for node in range(self.total_vertices): 31 | if self.degree[node] == 1: 32 | queue.append(node) 33 | 34 | total_nodes = self.total_vertices 35 | 36 | while total_nodes > 2: 37 | queue_len = len(queue) 38 | total_nodes -= queue_len 39 | 40 | while queue_len: 41 | node = queue.popleft() 42 | for child in self.graph[node]: 43 | self.degree[child] -= 1 44 | if self.degree[child] == 1: 45 | queue.append(child) 46 | queue_len -= 1 47 | 48 | return queue 49 | 50 | 51 | class Solution: 52 | def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]: 53 | if n == 1: return [0] 54 | graph = Graph(n, edges) 55 | return graph.get_min_height_nodes() 56 | 57 | ``` 58 | 59 | # Code Explanation 60 | -------------------------------------------------------------------------------- /LeetCode/Medium/Minimum Number of Arrows to Burst Balloons.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | class Solution: 10 | def findMinArrowShots(self, points: List[List[int]]) -> int: 11 | if not points: return 0 12 | points.sort() 13 | prev_start, prev_end = points[0] 14 | arrows_count = 1 15 | for start, end in points[1:]: 16 | if start > prev_end: 17 | arrows_count += 1 18 | prev_start, prev_end = start, end 19 | else: 20 | prev_end = min(prev_end, end) 21 | return arrows_count 22 | ``` 23 | 24 | # Code Explanation 25 | -------------------------------------------------------------------------------- /LeetCode/Medium/Number of Longest Increasing Subsequence.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/number-of-longest-increasing-subsequence/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | """ 10 | class Solution: 11 | def findNumberOfLIS(self, nums: List[int]) -> int: 12 | if not nums: return 0 13 | 14 | nums_len = len(nums) 15 | length = [1] * nums_len 16 | count = [1] * nums_len 17 | 18 | lis = 1 19 | 20 | for i in range(1, nums_len): 21 | for j in range(0, i): 22 | if nums[j] < nums[i]: 23 | if length[j]+1 > length[i]: 24 | length[i] = length[j] + 1 25 | count[i] = count[j] 26 | elif length[j]+1 == length[i]: 27 | count[i] += count[j] 28 | lis = max(lis, length[i]) 29 | 30 | ans = 0 31 | for index in range(nums_len): 32 | if length[index] == lis: 33 | ans += count[index] 34 | 35 | return ans 36 | ``` 37 | 38 | # Code Explanation 39 | -------------------------------------------------------------------------------- /LeetCode/Medium/Remove Covered Intervals.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/remove-covered-intervals/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | class Solution: 10 | def removeCoveredIntervals(self, intervals: List[List[int]]) -> int: 11 | intervals.sort(key = lambda x:x[0]) 12 | new_intervals = [intervals[0]] 13 | 14 | for interval in intervals[1:]: 15 | prev_start, prev_end = new_intervals[-1] 16 | curr_start, curr_end = interval 17 | 18 | if prev_start <= curr_start and curr_end <= prev_end: continue 19 | if prev_start == curr_start and prev_end < curr_end: new_intervals.pop() 20 | 21 | new_intervals.append(interval) 22 | 23 | return len(new_intervals) 24 | ``` 25 | 26 | # Code Explanation 27 | -------------------------------------------------------------------------------- /LeetCode/Medium/Remove Duplicate Letters.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/remove-duplicate-letters/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | class Solution: 10 | def removeDuplicateLetters(self, s: str) -> str: 11 | last_index = {} 12 | for index, char in enumerate(s): 13 | last_index[char] = index 14 | 15 | stack = [] 16 | visited = set() 17 | s_len = len(s) 18 | 19 | for index in range(s_len): 20 | char = s[index] 21 | 22 | if char in visited : continue 23 | 24 | while stack and stack[-1] > char and last_index[stack[-1]] > index: 25 | visited.remove(stack[-1]) 26 | stack.pop() 27 | 28 | stack.append(char) 29 | visited.add(char) 30 | 31 | return "".join(stack) 32 | ``` 33 | 34 | # Code Explanation 35 | -------------------------------------------------------------------------------- /LeetCode/Medium/Repeated DNA Sequences.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/repeated-dna-sequences/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | class Solution: 10 | def findRepeatedDnaSequences(self, s: str) -> List[str]: 11 | if not s: return [] 12 | s_len = len(s) 13 | 14 | start, end = 0, 10 15 | dna_freq = {} 16 | 17 | while end <= s_len: 18 | dna_seq = s[start:end] 19 | dna_freq[dna_seq] = dna_freq.get(dna_seq, 0) + 1 20 | start += 1 21 | end += 1 22 | 23 | ans = [] 24 | 25 | for seq, count in dna_freq.items(): 26 | if count > 1: 27 | ans += [seq] 28 | 29 | return ans 30 | ``` 31 | 32 | # Code Explanation 33 | -------------------------------------------------------------------------------- /LeetCode/Medium/Rotate Array.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/rotate-array/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | class Solution: 10 | 11 | def reverse_list(self, arr, start, end): 12 | while start <= end: 13 | arr[start], arr[end] = arr[end], arr[start] 14 | start += 1 15 | end -= 1 16 | 17 | def rotate(self, nums: List[int], k: int) -> None: 18 | """ 19 | Do not return anything, modify nums in-place instead. 20 | """ 21 | nums_len = len(nums) 22 | k = k % nums_len 23 | 24 | self.reverse_list(nums, -k, -1) 25 | self.reverse_list(nums, -nums_len, -k-1) 26 | self.reverse_list(nums, 0, nums_len-1) 27 | 28 | 29 | ``` 30 | 31 | # Code Explanation 32 | -------------------------------------------------------------------------------- /LeetCode/Medium/Rotate List.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/rotate-list/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | # Definition for singly-linked list. 10 | # class ListNode: 11 | # def __init__(self, val=0, next=None): 12 | # self.val = val 13 | # self.next = next 14 | class Solution: 15 | def rotateRight(self, head: ListNode, k: int) -> ListNode: 16 | total_nodes = 0 17 | curr = head 18 | while curr: 19 | curr = curr.next 20 | total_nodes += 1 21 | 22 | if total_nodes == 0: 23 | return None 24 | 25 | k = k % total_nodes 26 | 27 | start = head 28 | end = head 29 | while k: 30 | end = end.next 31 | k -= 1 32 | 33 | while end.next: 34 | start = start.next 35 | end = end.next 36 | 37 | end.next = head 38 | new_head = start.next 39 | start.next = None 40 | 41 | return new_head 42 | ``` 43 | 44 | # Code Explanation 45 | -------------------------------------------------------------------------------- /LeetCode/Medium/Search a 2D Matrix.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/search-a-2d-matrix/submissions/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ## Time Complexity : O(M*N) 9 | 10 | ```Python 11 | 12 | class Solution: 13 | def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: 14 | total_rows = len(matrix) 15 | if not total_rows: return False 16 | 17 | total_cols = len(matrix[0]) 18 | if not total_cols: return False 19 | 20 | for row in range(total_rows): 21 | for col in range(total_cols): 22 | if matrix[row][col] == target: 23 | return True 24 | 25 | return False 26 | ``` 27 | 28 | ## Code Explanation 29 | 30 | ## Time Complexity : O(M + N) 31 | 32 | ```Python 33 | 34 | ``` 35 | 36 | ## Code Explanation 37 | 38 | ## Time Complexity : O(logM + logN) 39 | 40 | ```Python 41 | 42 | ``` 43 | 44 | ## Code Explanation 45 | -------------------------------------------------------------------------------- /LeetCode/Medium/Sequential Digits.md: -------------------------------------------------------------------------------- 1 | Question Link : https://leetcode.com/problems/sequential-digits/ 2 | 3 | Approach : 4 | 5 | Solution: 6 | 7 | ```Python 8 | class Solution: 9 | def sequentialDigits(self, low: int, high: int) -> List[int]: 10 | ans = [] 11 | 12 | digits = "123456789" 13 | 14 | str_low = str(low) 15 | str_high = str(high) 16 | 17 | low_digits_count = len(str_low) 18 | high_digits_count = len(str_high) 19 | 20 | for size in range(low_digits_count, high_digits_count+1): 21 | for index in range(10-size): 22 | num = digits[index:index+size] 23 | if low <= int(num) <= high: 24 | ans.append(num) 25 | 26 | return ans 27 | ``` 28 | -------------------------------------------------------------------------------- /LeetCode/Medium/Sort List.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/sort-list/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | # Definition for singly-linked list. 10 | # class ListNode: 11 | # def __init__(self, val=0, next=None): 12 | # self.val = val 13 | # self.next = next 14 | 15 | class Solution: 16 | 17 | def find_mid(self, head): 18 | slow = head 19 | fast = head 20 | while fast.next and fast.next.next: 21 | slow = slow.next 22 | fast = fast.next.next 23 | mid = slow.next 24 | slow.next = None 25 | return mid 26 | 27 | def merge(self, left, right): 28 | if left.val <= right.val: 29 | top = left 30 | left = left.next 31 | else: 32 | top = right 33 | right = right.next 34 | 35 | curr = top 36 | 37 | while left and right: 38 | if left.val <= right.val: 39 | curr.next = left 40 | curr = left 41 | left = left.next 42 | else: 43 | curr.next = right 44 | curr = right 45 | right = right.next 46 | 47 | curr.next = left if left else right 48 | return top 49 | 50 | def merge_sort(self, head): 51 | if not head or not head.next: return head 52 | 53 | mid = self.find_mid(head) 54 | left = self.merge_sort(head) 55 | right = self.merge_sort(mid) 56 | 57 | return self.merge(left, right) 58 | 59 | 60 | def sortList(self, head: ListNode) -> ListNode: 61 | return self.merge_sort(head) 62 | 63 | ``` 64 | 65 | # Code Explanation 66 | -------------------------------------------------------------------------------- /LeetCode/Medium/Subarray Product Less Than K.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/subarray-product-less-than-k/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | class Solution: 10 | 11 | def get_subarr_count(self, start, end): 12 | ele_count = end-start 13 | return (ele_count * (ele_count+1)) // 2 14 | 15 | def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int: 16 | total_subarr = 0 17 | 18 | if k == 0: 19 | return total_subarr 20 | 21 | nums_len = len(nums) 22 | 23 | start = 0 24 | end = 0 25 | prev_end = 0 26 | 27 | curr_prod = 1 28 | 29 | while end < nums_len: 30 | curr_prod *= nums[end] 31 | 32 | while start < nums_len and curr_prod >= k: 33 | total_subarr += self.get_subarr_count(start, end) 34 | total_subarr -= self.get_subarr_count(start, prev_end) 35 | 36 | curr_prod /= nums[start] 37 | start += 1 38 | prev_end = end 39 | 40 | end += 1 41 | 42 | if curr_prod < k: 43 | total_subarr += self.get_subarr_count(start, end) 44 | total_subarr -= self.get_subarr_count(start, prev_end) 45 | 46 | 47 | return total_subarr 48 | ``` 49 | 50 | # Code Explanation 51 | -------------------------------------------------------------------------------- /LeetCode/Medium/Teemo Attacking.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/teemo-attacking/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | class Solution: 10 | def findPoisonedDuration(self, timeSeries: List[int], duration: int) -> int: 11 | if len(timeSeries) == 0: 12 | return 0 13 | 14 | total_duration = duration 15 | max_duration = timeSeries[0] + duration - 1 16 | 17 | for time in timeSeries[1:]: 18 | curr_duration = time + duration - 1 19 | 20 | if time <= max_duration: 21 | diff = curr_duration - max_duration 22 | else: 23 | diff = duration 24 | 25 | total_duration += diff 26 | max_duration = curr_duration 27 | 28 | return total_duration 29 | ``` 30 | 31 | # Code Explanation 32 | -------------------------------------------------------------------------------- /LeetCode/Medium/Word Break.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/word-break/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | class Solution: 10 | def wordBreak(self, s: str, wordDict: List[str]) -> bool: 11 | dict_words = set(wordDict) 12 | 13 | s_len = len(s) 14 | is_word = [False] * (s_len+1) 15 | is_word[0] = True 16 | 17 | for start in range(s_len): 18 | if is_word[start]: 19 | for end in range(start+1, s_len+1): 20 | if s[start:end] in dict_words: 21 | is_word[end] = True 22 | 23 | return is_word[-1] 24 | 25 | ``` 26 | 27 | # Code Explanation 28 | -------------------------------------------------------------------------------- /LeetCode/Premium/161. One Edit Distance.md: -------------------------------------------------------------------------------- 1 | # One Edit Distance 2 | 3 | **Problem Description:** 4 | 5 | Given two strings `s` and `t`, determine if they are both one edit distance apart. An edit is defined as an insertion, deletion, or substitution of a single character. 6 | 7 | **Example:** 8 | 9 | ```plaintext 10 | Input: s = "aDb", t = "adb" 11 | Output: true 12 | 13 | Input: s = "ab", t = "ab" 14 | Output: false 15 | ``` 16 | 17 | **Function Signature:** 18 | 19 | ```python 20 | class Solution: 21 | """ 22 | @param s: a string 23 | @param t: a string 24 | @return: true if they are both one edit distance apart or false 25 | """ 26 | def is_one_edit_distance(self, s: str, t: str) -> bool: 27 | s_len = len(s) 28 | t_len = len(t) 29 | 30 | if abs(s_len-t_len) > 1: 31 | return False 32 | 33 | # Always t will be smaller 34 | if s_len < t_len: 35 | s, t = t, s 36 | s_len, t_len = t_len, s_len 37 | 38 | # one char is inserted in s 39 | if s_len != t_len: 40 | s_index = 0 41 | t_index = 0 42 | mismatch_char_count = 0 43 | while t_index < t_len: 44 | if s[s_index] != t[t_index]: 45 | s_index += 1 46 | mismatch_char_count += 1 47 | if mismatch_char_count == 2: 48 | return False 49 | else: 50 | s_index += 1 51 | t_index += 1 52 | 53 | return mismatch_char_count <= 1 54 | 55 | # one mismatch character 56 | else: 57 | mismatch_char_count = 0 58 | for s_char, t_char in zip(s, t): 59 | if s_char != t_char: 60 | mismatch_char_count += 1 61 | if mismatch_char_count == 2: 62 | return False 63 | 64 | return mismatch_char_count == 1 65 | 66 | ``` 67 | 68 | **Constraints:** 69 | 70 | - The lengths of `s` and `t` are between 0 and 10^4. 71 | - Strings `s` and `t` consist of lowercase letters, uppercase letters, and digits. 72 | 73 | **Hints:** 74 | 75 | - Consider the possible cases: the strings have the same length, `s` is longer than `t` by one character, or `t` is longer than `s` by one character. 76 | - Iterate through the strings to find the first differing character and determine if the remaining substrings are identical after accounting for one edit. 77 | 78 | **Related Topics:** 79 | 80 | - String 81 | - Two Pointers 82 | 83 | **Source:** 84 | 85 | [LintCode Problem 640](https://www.lintcode.com/problem/640/description) 86 | -------------------------------------------------------------------------------- /LeetCode/Premium/253. Meeting Rooms II.md: -------------------------------------------------------------------------------- 1 | ## 253. Meeting Rooms II 2 | 3 | ### Problem Statement 4 | You are given an array of meeting time intervals `intervals`, where `intervals[i] = [start_i, end_i]`. Your task is to return the **minimum number of conference rooms required** to host all the meetings without overlap. 5 | 6 | ### Examples 7 | #### Example 1: 8 | **Input:** 9 | ```plaintext 10 | intervals = [[0,30],[5,10],[15,20]] 11 | ``` 12 | **Output:** 13 | ```plaintext 14 | 2 15 | ``` 16 | **Explanation:** 17 | - Meeting `[0,30]` overlaps with `[5,10]`, requiring two rooms. 18 | - Meeting `[15,20]` does not overlap with `[5,10]`, but still overlaps with `[0,30]`, so two rooms are needed in total. 19 | 20 | #### Example 2: 21 | **Input:** 22 | ```plaintext 23 | intervals = [[7,10],[2,4]] 24 | ``` 25 | **Output:** 26 | ```plaintext 27 | 1 28 | ``` 29 | **Explanation:** 30 | - Meetings `[7,10]` and `[2,4]` do not overlap, so only one room is required. 31 | 32 | ### Constraints: 33 | - `1 <= intervals.length <= 10^4` 34 | - `0 <= start_i < end_i <= 10^6` 35 | 36 | ### Follow-Up Questions 37 | 1. Can you solve this problem with a time complexity better than `O(n^2)`? 38 | 2. How would you modify your approach if you also needed to return which meetings go into which rooms? 39 | 3. Can this problem be solved using a heap (priority queue)? If so, how? 40 | 4. How would you handle real-world scheduling where meetings can be modified or canceled dynamically? 41 | 5. What if the meeting times were represented in a different format, such as timestamps or a 24-hour format? 42 | 43 | ### Python Solution: 44 | 45 | ```python 46 | class Solution: 47 | def minMeetingRooms(self, intervals: List[List[int]]) -> int: 48 | intervals.sort(key=lambda x:x[0]) 49 | min_heap = [] 50 | for start, end in intervals: 51 | if min_heap and min_heap[0] <= start: 52 | heappop(min_heap) 53 | heappush(min_heap, end) 54 | return len(min_heap) 55 | 56 | ``` 57 | -------------------------------------------------------------------------------- /LeetCode/Premium/2534. Time Taken to Cross the Door.md: -------------------------------------------------------------------------------- 1 | ## 2534. Time Taken to Cross the Door 2 | 3 | ### Problem Statement 4 | You are given `n` persons numbered from `0` to `n - 1` and a door. Each person can enter or exit through the door once, taking one second. 5 | 6 | You are given: 7 | - A **non-decreasing** integer array `arrival` of size `n`, where `arrival[i]` represents the arrival time of the `i`th person at the door. 8 | - An integer array `state` of size `n`, where `state[i]` is: 9 | - `0` if person `i` wants to enter. 10 | - `1` if person `i` wants to exit. 11 | 12 | #### Rules for Using the Door 13 | - If **two or more persons** want to use the door at the same time, they follow these rules: 14 | 1. If the door was **not used** in the previous second, the person who wants to **exit** goes first. 15 | 2. If the door was **previously used for entering**, the person who wants to **enter** goes first. 16 | 3. If the door was **previously used for exiting**, the person who wants to **exit** goes first. 17 | 4. If multiple persons want to go in the **same direction**, the person with the **smallest index** goes first. 18 | - Only **one person** can cross the door at each second. 19 | - A person may arrive and **wait** before crossing to follow the above rules. 20 | 21 | ### Output 22 | Return an array `answer` of size `n` where `answer[i]` represents the **time** at which the `i`th person crosses the door. 23 | 24 | ### Examples 25 | 26 | #### Example 1 27 | **Input:** 28 | ```plaintext 29 | arrival = [0,1,1,2,4] 30 | state = [0,1,0,0,1] 31 | ``` 32 | 33 | **Output:** 34 | ```plaintext 35 | [0,3,1,2,4] 36 | ``` 37 | 38 | **Explanation:** 39 | - At `t = 0`: Person `0` enters (only one at the door). 40 | - At `t = 1`: Person `1` wants to exit, Person `2` wants to enter. Since the door was **previously used for entering**, Person `2` enters. 41 | - At `t = 2`: Person `1` wants to exit, Person `3` wants to enter. Since the door was **previously used for entering**, Person `3` enters. 42 | - At `t = 3`: Person `1` is the only one left, so they exit. 43 | - At `t = 4`: Person `4` is the only one left, so they exit. 44 | 45 | #### Example 2 46 | **Input:** 47 | ```plaintext 48 | arrival = [0,0,0] 49 | state = [1,0,1] 50 | ``` 51 | 52 | **Output:** 53 | ```plaintext 54 | [0,2,1] 55 | ``` 56 | 57 | **Explanation:** 58 | - At `t = 0`: Person `1` wants to enter, Persons `0` and `2` want to exit. Since the door was **not used before**, exit goes first. Person `0` exits. 59 | - At `t = 1`: Person `1` wants to enter, Person `2` wants to exit. Since the door was **previously used for exiting**, Person `2` exits. 60 | - At `t = 2`: Person `1` is the only one left, so they enter. 61 | 62 | ### Constraints 63 | - `n == arrival.length == state.length` 64 | - `1 <= n <= 10^5` 65 | - `0 <= arrival[i] <= n` 66 | - `arrival` is sorted in **non-decreasing** order. 67 | - `state[i]` is either `0` or `1`. 68 | 69 | ### Follow-up Questions 70 | - Can you optimize the solution to run in **O(n)** time complexity? 71 | - How would your solution behave if `arrival` were not sorted? 72 | - How would you handle scenarios where multiple people arrive at the same second but have different states? 73 | - Can you implement the solution using a **single queue** or two separate queues (one for entering and one for exiting)? 74 | 75 | ### Python Solution: 76 | 77 | ```python 78 | class Solution: 79 | def timeTaken(self, arrival: List[int], state: List[int]) -> List[int]: 80 | entry_queue = deque() 81 | exit_queue = deque() 82 | 83 | prev_door_state = None 84 | answer = [None] * len(arrival) 85 | 86 | waiting_queue = deque() 87 | for person, (arrival_time, door_state) in enumerate(zip(arrival, state)): 88 | waiting_queue.append((arrival_time, door_state, person)) 89 | 90 | 91 | time = 0 92 | while waiting_queue or entry_queue or exit_queue: 93 | person = None 94 | # move persons from waiting queue 95 | while waiting_queue and waiting_queue[0][0] <= time: 96 | arrival_time, door_state, person = waiting_queue.popleft() 97 | if door_state == 0: 98 | entry_queue.append(person) 99 | else: 100 | exit_queue.append(person) 101 | 102 | if entry_queue and exit_queue: 103 | if prev_door_state == None or prev_door_state == 1: 104 | person = exit_queue.popleft() 105 | else: 106 | person = entry_queue.popleft() 107 | 108 | elif entry_queue: 109 | person = entry_queue.popleft() 110 | prev_door_state = 0 111 | 112 | elif exit_queue: 113 | person = exit_queue.popleft() 114 | prev_door_state = 1 115 | else: 116 | prev_door_state = None 117 | 118 | if person != None: 119 | answer[person] = time 120 | 121 | time += 1 122 | 123 | return answer 124 | ``` 125 | 126 | 127 | -------------------------------------------------------------------------------- /LeetCode/Premium/266. Palindrome Permutation.md: -------------------------------------------------------------------------------- 1 | # Palindrome Permutation 2 | 3 | **Problem Description:** 4 | 5 | Given a string, determine if a permutation of the string could form a palindrome. 6 | 7 | **Example:** 8 | 9 | ```plaintext 10 | Input: "code" 11 | Output: False 12 | 13 | Input: "aab" 14 | Output: True 15 | ``` 16 | 17 | **Python Solution** 18 | 19 | ```python 20 | from collections import Counter 21 | class Solution: 22 | """ 23 | @param s: the given string 24 | @return: if a permutation of the string could form a palindrome 25 | """ 26 | def can_permute_palindrome(self, s: str) -> bool: 27 | freq = Counter(s) 28 | odd_count = 0 29 | for char, count in freq.items(): 30 | if count % 2 != 0: 31 | odd_count += 1 32 | if odd_count == 2: 33 | return False 34 | return True 35 | ``` 36 | 37 | **Constraints:** 38 | 39 | - The input string `s` consists of lowercase English letters. 40 | 41 | **Hints:** 42 | 43 | - Consider the properties of a palindrome. How do the frequencies of characters affect the possibility of forming a palindrome? 44 | - Utilize a data structure to count character occurrences efficiently. 45 | 46 | **Related Topics:** 47 | 48 | - Hash Table 49 | - String 50 | 51 | **Source:** 52 | 53 | [LintCode Problem 916](https://www.lintcode.com/problem/916/) 54 | -------------------------------------------------------------------------------- /LeetCode/Premium/346. Moving Average from Data Stream.md: -------------------------------------------------------------------------------- 1 | # 346. Moving Average from Data Stream 2 | 3 | ## Problem Statement 4 | Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window. 5 | 6 | ## Implement the `MovingAverage` class: 7 | 8 | - `MovingAverage(int size)`: Initializes the object with the size of the window size. 9 | - `double next(int val)`: Returns the moving average of the last `size` values of the stream. 10 | 11 | --- 12 | 13 | ## Example 14 | 15 | ### **Input:** 16 | ```plaintext 17 | ["MovingAverage", "next", "next", "next", "next"] 18 | [[3], [1], [10], [3], [5]] 19 | ``` 20 | 21 | ### **Output:** 22 | ```plaintext 23 | [null, 1.0, 5.5, 4.66667, 6.0] 24 | ``` 25 | 26 | ### **Explanation:** 27 | ```python 28 | MovingAverage movingAverage = new MovingAverage(3); 29 | movingAverage.next(1); // return 1.0 = 1 / 1 30 | movingAverage.next(10); // return 5.5 = (1 + 10) / 2 31 | movingAverage.next(3); // return 4.66667 = (1 + 10 + 3) / 3 32 | movingAverage.next(5); // return 6.0 = (10 + 3 + 5) / 3 33 | ``` 34 | 35 | --- 36 | 37 | ## Constraints: 38 | - `1 <= size <= 1000` 39 | - `-10^5 <= val <= 10^5` 40 | - At most `10^4` calls will be made to `next()`. 41 | 42 | 43 | ### Python Solution: 44 | 45 | ```python 46 | class MovingAverage: 47 | 48 | def __init__(self, size: int): 49 | self.queue = deque() 50 | self.queue_sum = 0 51 | self.queue_size = 0 52 | self.window_size = size 53 | 54 | 55 | def next(self, val: int) -> float: 56 | self.queue.append(val) 57 | self.queue_sum += val 58 | self.queue_size += 1 59 | 60 | while self.queue and self.queue_size > self.window_size: 61 | first_ele = self.queue.popleft() 62 | self.queue_sum -= first_ele 63 | self.queue_size -= 1 64 | 65 | return self.queue_sum / self.queue_size 66 | 67 | 68 | # Your MovingAverage object will be instantiated and called as such: 69 | # obj = MovingAverage(size) 70 | # param_1 = obj.next(val) 71 | ``` 72 | 73 | -------------------------------------------------------------------------------- /LeetCode/Premium/364. Nested List Weight Sum II.md: -------------------------------------------------------------------------------- 1 | ## 364. Nested List Weight Sum II 2 | 3 | ### Problem Statement 4 | You are given a nested list of integers `nestedList`. Each element is either an integer or a list whose elements may also be integers or other lists. 5 | 6 | The **depth** of an integer is the number of lists that it is inside of. For example, the nested list `[1,[2,2],[[3],2],1]` has each integer's value set to its depth. Let `maxDepth` be the maximum depth of any integer. 7 | 8 | The **weight** of an integer is calculated as: 9 | ``` 10 | weight = maxDepth - (depth of the integer) + 1 11 | ``` 12 | Return the sum of each integer in `nestedList` multiplied by its weight. 13 | 14 | ### Examples 15 | #### Example 1: 16 | **Input:** 17 | ```plaintext 18 | nestedList = [[1,1],2,[1,1]] 19 | ``` 20 | **Output:** 21 | ```plaintext 22 | 8 23 | ``` 24 | **Explanation:** 25 | - Four `1`s with a weight of `1` 26 | - One `2` with a weight of `2` 27 | 28 | Calculation: 29 | ```plaintext 30 | 1*1 + 1*1 + 2*2 + 1*1 + 1*1 = 8 31 | ``` 32 | 33 | #### Example 2: 34 | **Input:** 35 | ```plaintext 36 | nestedList = [1,[4,[6]]] 37 | ``` 38 | **Output:** 39 | ```plaintext 40 | 17 41 | ``` 42 | **Explanation:** 43 | - `1` is at depth `3`, weight = `3` 44 | - `4` is at depth `2`, weight = `2` 45 | - `6` is at depth `1`, weight = `1` 46 | 47 | Calculation: 48 | ```plaintext 49 | 1*3 + 4*2 + 6*1 = 17 50 | ``` 51 | 52 | ### Constraints: 53 | - `1 <= nestedList.length <= 50` 54 | - The values of the integers in the nested list are in the range `[-100, 100]`. 55 | - The maximum depth of any integer is `<= 50`. 56 | - There are no empty lists. 57 | 58 | ### Follow-Up Questions 59 | 1. Can you solve this problem using **BFS** instead of **DFS**? 60 | 2. How does the complexity of your approach scale with increasing depth? 61 | 3. What if the list were extremely large? How would you optimize your solution? 62 | 4. How would you modify your solution if the problem asked for a different weight calculation method? 63 | 5. Can this problem be related to **tree traversal** techniques? 64 | 65 | 66 | ### Python Solution: 67 | 68 | ```python 69 | # """ 70 | # This is the interface that allows for creating nested lists. 71 | # You should not implement it, or speculate about its implementation 72 | # """ 73 | #class NestedInteger: 74 | # def __init__(self, value=None): 75 | # """ 76 | # If value is not specified, initializes an empty list. 77 | # Otherwise initializes a single integer equal to value. 78 | # """ 79 | # 80 | # def isInteger(self): 81 | # """ 82 | # @return True if this NestedInteger holds a single integer, rather than a nested list. 83 | # :rtype bool 84 | # """ 85 | # 86 | # def add(self, elem): 87 | # """ 88 | # Set this NestedInteger to hold a nested list and adds a nested integer elem to it. 89 | # :rtype void 90 | # """ 91 | # 92 | # def setInteger(self, value): 93 | # """ 94 | # Set this NestedInteger to hold a single integer equal to value. 95 | # :rtype void 96 | # """ 97 | # 98 | # def getInteger(self): 99 | # """ 100 | # @return the single integer that this NestedInteger holds, if it holds a single integer 101 | # Return None if this NestedInteger holds a nested list 102 | # :rtype int 103 | # """ 104 | # 105 | # def getList(self): 106 | # """ 107 | # @return the nested list that this NestedInteger holds, if it holds a nested list 108 | # Return None if this NestedInteger holds a single integer 109 | # :rtype List[NestedInteger] 110 | # """ 111 | 112 | class Solution: 113 | 114 | def get_max_depth(self, nested_list, depth): 115 | self.max_depth = max(self.max_depth, depth) 116 | for ele in nested_list: 117 | if not ele.isInteger(): 118 | ele_list = ele.getList() 119 | self.get_max_depth(ele_list, depth+1) 120 | 121 | def get_weighted_num_sum(self, ele, depth): 122 | weighted_sum = 0 123 | if ele.isInteger(): 124 | return ele.getInteger() * (self.max_depth - depth + 1) 125 | else: 126 | nested_list = ele.getList() 127 | for nested_ele in nested_list: 128 | weighted_sum += self.get_weighted_num_sum(nested_ele, depth+1) 129 | return weighted_sum 130 | 131 | 132 | def depthSumInverse(self, nestedList: List[NestedInteger]) -> int: 133 | total_sum = 0 134 | self.max_depth = 1 135 | self.get_max_depth(nestedList, 1) 136 | 137 | for ele in nestedList: 138 | curr_sum = self.get_weighted_num_sum(ele, 1) 139 | total_sum += curr_sum 140 | 141 | return total_sum 142 | 143 | ``` 144 | -------------------------------------------------------------------------------- /LeetCode/Premium/444. Sequence Reconstruction.md: -------------------------------------------------------------------------------- 1 | ## 444. Sequence Reconstruction 2 | 3 | ### Problem Statement 4 | You are given an integer array `nums` of length `n`, where `nums` is a permutation of the integers in the range `[1, n]`. You are also given a 2D integer array `sequences`, where `sequences[i]` is a subsequence of `nums`. 5 | 6 | Your task is to determine if `nums` is the shortest possible and the **only** supersequence. The shortest supersequence is a sequence with the shortest length that contains all `sequences[i]` as subsequences. There could be multiple valid shortest supersequences for the given array `sequences`. 7 | 8 | ### Examples 9 | #### Example 1: 10 | **Input:** 11 | ```plaintext 12 | nums = [1,2,3], sequences = [[1,2],[1,3]] 13 | ``` 14 | **Output:** 15 | ```plaintext 16 | false 17 | ``` 18 | **Explanation:** 19 | There are two possible shortest supersequences: `[1,2,3]` and `[1,3,2]`. Since `nums` is not the only shortest supersequence, we return `false`. 20 | 21 | #### Example 2: 22 | **Input:** 23 | ```plaintext 24 | nums = [1,2,3], sequences = [[1,2]] 25 | ``` 26 | **Output:** 27 | ```plaintext 28 | false 29 | ``` 30 | **Explanation:** 31 | The shortest possible supersequence is `[1,2]`. Since `nums` is `[1,2,3]`, which is not the shortest, we return `false`. 32 | 33 | #### Example 3: 34 | **Input:** 35 | ```plaintext 36 | nums = [1,2,3], sequences = [[1,2],[1,3],[2,3]] 37 | ``` 38 | **Output:** 39 | ```plaintext 40 | true 41 | ``` 42 | **Explanation:** 43 | The shortest possible supersequence is `[1,2,3]`, and it is the only valid one. Therefore, we return `true`. 44 | 45 | ### Constraints: 46 | - `n == nums.length` 47 | - `1 <= n <= 10^4` 48 | - `nums` is a permutation of all the integers in the range `[1, n]`. 49 | - `1 <= sequences.length <= 10^4` 50 | - `1 <= sequences[i].length <= 10^4` 51 | - `1 <= sum(sequences[i].length) <= 10^5` 52 | - `1 <= sequences[i][j] <= n` 53 | - All arrays in `sequences` are unique. 54 | - `sequences[i]` is a subsequence of `nums`. 55 | 56 | ### Follow-Up Questions 57 | 1. How can you efficiently reconstruct the shortest supersequence from `sequences`? 58 | 2. Can this problem be solved using graph theory? If so, how? 59 | 3. What is the time complexity of your solution? 60 | 4. How would your solution scale if `n` were much larger (e.g., `10^6`)? 61 | 5. How would you modify your approach if `nums` were not guaranteed to be a permutation? 62 | 63 | ### Python Solution 64 | 65 | ```python 66 | class Node: 67 | def __init__(self, val): 68 | self.val = val 69 | self.children = [] 70 | self.in_degree = 0 71 | 72 | def __repr__(self): 73 | return f"val:{self.val} | degree: {self.in_degree}" 74 | 75 | 76 | class Graph: 77 | def __init__(self, nums, edges): 78 | self.nums = nums 79 | self.edges = edges 80 | 81 | self.graph = {} 82 | self.topological_sort = [] 83 | 84 | self.build_nodes(self.nums) 85 | self.build_graph(self.edges) 86 | 87 | def get_or_create_node(self, val): 88 | if val not in self.graph: 89 | self.graph[val] = Node(val) 90 | return self.graph[val] 91 | 92 | def build_nodes(self, nums): 93 | for val in nums: 94 | self.get_or_create_node(val) 95 | 96 | def build_graph(self, edges_list): 97 | for edges in edges_list: 98 | for index in range(len(edges)-1): 99 | parent_val, child_val = edges[index], edges[index+1] 100 | parent = self.get_or_create_node(parent_val) 101 | child = self.get_or_create_node(child_val) 102 | parent.children.append(child) 103 | child.in_degree += 1 104 | 105 | def get_nodes_with_zero_in_degree(self): 106 | zero_degree_nodes = [] 107 | for val, node in self.graph.items(): 108 | if node.in_degree == 0: 109 | zero_degree_nodes.append(node) 110 | return zero_degree_nodes 111 | 112 | def get_topological_sort(self): 113 | starting_nodes = self.get_nodes_with_zero_in_degree() 114 | if len(starting_nodes) != 1: 115 | return self.topological_sort 116 | 117 | queue = deque(starting_nodes) 118 | 119 | while queue: 120 | node = queue.popleft() 121 | self.topological_sort.append(node) 122 | 123 | child_appended = 0 124 | for child in node.children: 125 | child.in_degree -= 1 126 | if child.in_degree == 0: 127 | queue.append(child) 128 | child_appended += 1 129 | 130 | if child_appended == 2: 131 | return self.topological_sort 132 | 133 | 134 | return self.topological_sort 135 | 136 | 137 | class Solution: 138 | def sequenceReconstruction(self, nums: List[int], sequences: List[List[int]]) -> bool: 139 | graph = Graph(nums, sequences) 140 | topological_sort = graph.get_topological_sort() 141 | topo_nums = [ node.val for node in topological_sort] 142 | return topo_nums == nums 143 | ``` 144 | -------------------------------------------------------------------------------- /LeetCode/Premium/Missing Ranges.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/missing-ranges/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | class Solution: 10 | """ 11 | @param: nums: a sorted integer array 12 | @param: lower: An integer 13 | @param: upper: An integer 14 | @return: a list of its missing ranges 15 | """ 16 | 17 | def append_range(self, diff, lower , upper=None): 18 | if diff == 2: 19 | self.missing_ranges += [str(lower)] 20 | elif diff > 2: 21 | self.missing_ranges += ["{0}->{1}".format(lower, upper)] 22 | 23 | 24 | def findMissingRanges(self, nums, lower, upper): 25 | # write your code here 26 | self.missing_ranges = [] 27 | 28 | if not nums: 29 | if lower == upper: 30 | return [str(lower)] 31 | return ["{0}->{1}".format(lower, upper)] 32 | 33 | nums_len = len(nums) 34 | 35 | diff = nums[0]-lower + 1 36 | self.append_range(diff, lower, nums[0]-1) 37 | 38 | for index in range(nums_len-1): 39 | diff = nums[index+1] - nums[index] 40 | self.append_range(diff, nums[index]+1, nums[index+1]-1) 41 | 42 | diff = upper - nums[-1] + 1 43 | self.append_range(diff, nums[-1]+1, upper) 44 | 45 | return self.missing_ranges 46 | ``` 47 | 48 | # Code Explanation 49 | -------------------------------------------------------------------------------- /LeetCode/Premium/Nested List Weight Sum.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/nested-list-weight-sum/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | """ 10 | This is the interface that allows for creating nested lists. 11 | You should not implement it, or speculate about its implementation 12 | 13 | class NestedInteger(object): 14 | def isInteger(self): 15 | # @return {boolean} True if this NestedInteger holds a single integer, 16 | # rather than a nested list. 17 | 18 | def getInteger(self): 19 | # @return {int} the single integer that this NestedInteger holds, 20 | # if it holds a single integer 21 | # Return None if this NestedInteger holds a nested list 22 | 23 | def getList(self): 24 | # @return {NestedInteger[]} the nested list that this NestedInteger holds, 25 | # if it holds a nested list 26 | # Return None if this NestedInteger holds a single integer 27 | """ 28 | 29 | 30 | class Solution(object): 31 | # @param {NestedInteger[]} nestedList a list of NestedInteger Object 32 | # @return {int} an integer 33 | def depthSum(self, nestedList): 34 | # Write your code here 35 | 36 | def get_weigth_sum(nested_list, depth): 37 | if nested_list.isInteger(): 38 | return nested_list.getInteger() * depth 39 | 40 | temp_sum = 0 41 | for temp in nested_list.getList(): 42 | temp_sum += get_weigth_sum(temp, depth+1) 43 | 44 | return temp_sum 45 | 46 | weight_sum = 0 47 | 48 | for val in nestedList: 49 | weight_sum += get_weigth_sum(val, 1) 50 | 51 | return weight_sum 52 | 53 | 54 | ``` 55 | 56 | # Code Explanation 57 | -------------------------------------------------------------------------------- /LeetCode/Premium/Palindrome Permutation.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/palindrome-permutation/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | 10 | from collections import Counter 11 | class Solution: 12 | """ 13 | @param s: the given string 14 | @return: if a permutation of the string could form a palindrome 15 | """ 16 | def canPermutePalindrome(self, s): 17 | # write your code here 18 | freq = Counter(s) 19 | odd_count = 0 20 | for count in freq.values(): 21 | if count % 2: 22 | odd_count += 1 23 | if odd_count == 2: 24 | return False 25 | return True 26 | 27 | ``` 28 | 29 | # Code Explanation 30 | -------------------------------------------------------------------------------- /LeetCode/Premium/Plus One Linked List.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/plus-one-linked-list/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | """ 10 | Definition of ListNode 11 | class ListNode(object): 12 | def __init__(self, val, next=None): 13 | self.val = val 14 | self.next = next 15 | """ 16 | 17 | class Solution: 18 | """ 19 | @param head: the first Node 20 | @return: the answer after plus one 21 | """ 22 | def plusOne(self, head): 23 | prev_node = None 24 | curr_node = head 25 | 26 | while curr_node: 27 | curr_node.prev = prev_node 28 | prev_node = curr_node 29 | curr_node = curr_node.next 30 | 31 | carry = 1 32 | curr_node = prev_node 33 | 34 | while curr_node: 35 | curr_val = curr_node.val + carry 36 | digit = curr_val % 10 37 | carry = 1 if curr_val > 9 else 0 38 | curr_node.val = digit 39 | curr_node = curr_node.prev 40 | 41 | if carry: 42 | return ListNode(1, head) 43 | 44 | return head 45 | ``` 46 | 47 | # Code Explanation 48 | -------------------------------------------------------------------------------- /LeetCode/Premium/Shortest Word Distance.md: -------------------------------------------------------------------------------- 1 | # Question Link 2 | https://leetcode.com/problems/shortest-word-distance/ 3 | 4 | # Approach 5 | 6 | # Python Code 7 | 8 | ```Python 9 | class Solution: 10 | """ 11 | @param words: a list of words 12 | @param word1: a string 13 | @param word2: a string 14 | @return: the shortest distance between word1 and word2 in the list 15 | """ 16 | 17 | def shortestDistance(self, words, word1, word2): 18 | # Write your code here 19 | word1_indices = [] 20 | word2_indices = [] 21 | for index, word in enumerate(words): 22 | if word == word1: 23 | word1_indices += [index] 24 | elif word == word2: 25 | word2_indices += [index] 26 | 27 | shortest_distance = float('inf') 28 | 29 | for word1_index in word1_indices: 30 | for word2_index in word2_indices: 31 | shortest_distance = min(shortest_distance, abs(word1_index-word2_index)) 32 | 33 | return shortest_distance 34 | ``` 35 | 36 | # Code Explanation 37 | -------------------------------------------------------------------------------- /LeetCode/Premium/Valid Word Square.md: -------------------------------------------------------------------------------- 1 | # Valid Word Square 2 | 3 | ## Description 4 | Given a sequence of words, check whether it forms a valid word square. A sequence of words forms a valid word square if the k-th row and k-th column read the exact same string, where 0 ≤ k < max(numRows, numColumns). 5 | 6 | ## Example 1 7 | ``` 8 | Input: 9 | [ 10 | "abcd", 11 | "bnrt", 12 | "crmy", 13 | "dtye" 14 | ] 15 | 16 | Output: 17 | true 18 | 19 | Explanation: 20 | The first row and first column both read "abcd". 21 | The second row and second column both read "bnrt". 22 | The third row and third column both read "crmy". 23 | The fourth row and fourth column both read "dtye". 24 | Therefore, it is a valid word square. 25 | ``` 26 | 27 | ## Example 2 28 | ``` 29 | Input: 30 | [ 31 | "abcd", 32 | "bnrt", 33 | "crm", 34 | "dt" 35 | ] 36 | 37 | Output: 38 | true 39 | 40 | Explanation: 41 | The first row and first column both read "abcd". 42 | The second row and second column both read "bnrt". 43 | The third row and third column both read "crm". 44 | The fourth row and fourth column both read "dt". 45 | Therefore, it is a valid word square. 46 | ``` 47 | 48 | ## Example 3 49 | ``` 50 | Input: 51 | [ 52 | "ball", 53 | "area", 54 | "read", 55 | "lady" 56 | ] 57 | 58 | Output: 59 | false 60 | 61 | Explanation: 62 | The second row reads "area" while the second column reads "alrd". 63 | Therefore, it is NOT a valid word square. 64 | ``` 65 | 66 | ## Solution 67 | 68 | ```Python 69 | from typing import ( 70 | List, 71 | ) 72 | from collections import defaultdict 73 | 74 | class Solution: 75 | """ 76 | @param words: a list of string 77 | @return: a boolean 78 | """ 79 | def valid_word_square(self, words: List[str]) -> bool: 80 | row_word_len = defaultdict(int) 81 | col_word_len = defaultdict(int) 82 | total_rows = len(words) 83 | total_cols = len(words[0]) 84 | 85 | for index, word in enumerate(words): 86 | word_len = len(word) 87 | row_word_len[index] = word_len 88 | for col in range(word_len): 89 | col_word_len[col] += 1 90 | 91 | k = max(total_rows, total_cols) 92 | for index in range(k): 93 | row_len = row_word_len[index] 94 | col_len = col_word_len[index] 95 | if row_len != col_len: 96 | return False 97 | 98 | row_word = "" 99 | for col in range(row_len): 100 | row_word += words[index][col] 101 | 102 | col_word = "" 103 | for row in range(col_len): 104 | col_word += words[row][index] 105 | 106 | if row_word != col_word: 107 | return False 108 | 109 | return True 110 | ``` 111 | 112 | -------------------------------------------------------------------------------- /LeetCode/Premium/Word Squares.md: -------------------------------------------------------------------------------- 1 | # Word Squares 2 | 3 | ## Problem Statement 4 | A **word square** is an arrangement of words in a square grid such that the \( k \)-th row and \( k \)-th column contain the same string, for all valid \( k \). 5 | 6 | Given a list of unique words, return all possible word squares. 7 | 8 | ## Example 9 | 10 | ### Input: 11 | ```plaintext 12 | words = ["area", "lead", "wall", "lady", "ball"] 13 | ``` 14 | 15 | ### Output: 16 | ```plaintext 17 | [ 18 | ["wall", 19 | "area", 20 | "lead", 21 | "lady"], 22 | 23 | ["ball", 24 | "area", 25 | "lead", 26 | "lady"] 27 | ] 28 | ``` 29 | 30 | ## Constraints 31 | - The number of words is at least **1** and at most **1000**. 32 | - All words have the **exact same length**. 33 | - The length of each word is at least **1** and at most **5**. 34 | - Each word consists of **only lowercase English letters** (a-z). 35 | 36 | ## Approach 37 | To efficiently generate word squares, consider using a **Trie (prefix tree)** for quick prefix lookups. This helps in pruning invalid paths early. 38 | 39 | ### Steps: 40 | 1. **Build a Trie** from the given words. 41 | 2. **Use Depth-First Search (DFS)** to construct word squares. 42 | 3. **Backtracking** ensures only valid word sequences are explored. 43 | 44 | ## Python Solution 45 | ```python 46 | from collections import deque 47 | 48 | class TrieNode: 49 | def __init__(self, char): 50 | self.char = char 51 | self.children = {} 52 | self.prefix_words_list = [] 53 | 54 | def __repr__(self): 55 | return f"{self.char} -> {self.prefix_words_list}" 56 | 57 | class Trie: 58 | def __init__(self): 59 | self.root = TrieNode('*') 60 | 61 | def add_word_to_trie(self, word): 62 | node = self.root 63 | for char in word: 64 | if char in node.children: 65 | node = node.children.get(char) 66 | else: 67 | child_node = TrieNode(char) 68 | node.children[char] = child_node 69 | node = child_node 70 | node.prefix_words_list.append(word) 71 | 72 | def find_word_with_prefix(self, prefix): 73 | node = self.root 74 | for char in prefix: 75 | if char in node.children: 76 | node = node.children[char] 77 | else: 78 | return [] # prefix does not exist in trie 79 | return node.prefix_words_list 80 | 81 | def print_trie(self): 82 | node = self.root 83 | prefix = "" 84 | curr_level = deque() 85 | next_level = deque([(prefix, node)]) 86 | 87 | while next_level: 88 | curr_level = next_level 89 | print([(prefix, node) for prefix, node in curr_level]) 90 | 91 | next_level = deque() 92 | while curr_level: 93 | prefix, node = curr_level.popleft() 94 | for char, child in node.children.items(): 95 | next_level.append((prefix+char, child)) 96 | 97 | 98 | class Solution: 99 | """ 100 | @param words: a set of words without duplicates 101 | @return: all word squares 102 | we will sort your return value in output 103 | """ 104 | 105 | def backtrack(self, square, squares): 106 | if len(square) == self.word_length: 107 | squares.append(square[:]) 108 | return None 109 | 110 | index = len(square) 111 | prefix = "" 112 | for word in square: 113 | prefix += word[index] 114 | 115 | prefix_words = self.trie.find_word_with_prefix(prefix) 116 | # print(prefix, prefix_words) 117 | for word in prefix_words: 118 | square.append(word) 119 | self.backtrack(square, squares) 120 | square.pop() 121 | 122 | 123 | def word_squares(self, words): 124 | self.trie = Trie() 125 | for word in words: 126 | self.trie.add_word_to_trie(word) 127 | # trie.print_trie() 128 | self.word_length = len(words[0]) 129 | 130 | squares = [] 131 | for word in words: 132 | self.backtrack([word], squares) 133 | 134 | return squares 135 | ``` 136 | 137 | ## Complexity Analysis 138 | - **Trie Construction**: \( O(N \cdot L) \) where \( N \) is the number of words and \( L \) is the word length. 139 | - **Backtracking Search**: \( O(N \cdot L) \) calls in the worst case. 140 | - **Total Complexity**: Approximately \( O(NL) \) for a reasonable input size. 141 | 142 | ## Alternative Approaches 143 | - **Using a HashMap** instead of a Trie for prefix lookups. 144 | - **Iterative Breadth-First Search (BFS)** for word square construction. 145 | 146 | ## Summary 147 | Using a Trie with DFS ensures an efficient solution by pruning invalid paths early, making the algorithm optimal for constructing word squares. 148 | 149 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Data Structures And Algorithms 2 | 3 | ## Collection of Python solutions for various Data Structures And Algorithms questions. 4 | 5 | - [LeetCode](https://leetcode.com/vikasviki489/) 6 | + PREMIUM 7 | * [Nested List Weight Sum](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Premium/Nested%20List%20Weight%20Sum.md) 8 | * [Palindrome Permutation](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Premium/Palindrome%20Permutation.md) 9 | * [Missing Ranges](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Premium/Missing%20Ranges.md) 10 | * [Shortest Word Distance](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Premium/Shortest%20Word%20Distance.md) 11 | + EASY 12 | * [Flipping an Image](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Easy/Flipping%20an%20Image.md) 13 | * [Binary Tree Tilt](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Easy/Binary%20Tree%20Tilt.md) 14 | * [Minimum Cost to Move Chips to The Same Position](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Easy/Minimum%20Cost%20to%20Move%20Chips%20to%20The%20Same%20Position.md) 15 | * [Consecutive Characters](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Easy/Consecutive%20Characters.md) 16 | * [Convert Binary Number in a Linked List to Integer](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Easy/Convert%20Binary%20Number%20in%20a%20Linked%20List%20to%20Integer.md) 17 | * [Summary Ranges](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Easy/Summary%20Ranges.md) 18 | * [Minimum Depth of Binary Tree](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Easy/Minimum%20Depth%20of%20Binary%20Tree.md) 19 | * [Buddy Strings](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Easy/Buddy%20Strings.md) 20 | * [Binary Search](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Easy/Binary%20Search.md) 21 | * [Complement of Base 10 Integer](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Easy/Complement%20of%20Base%2010%20Integer.md) 22 | * [Number of Recent Calls](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Easy/Number%20of%20Recent%20Calls.md) 23 | * [Find the Difference](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Easy/Find%20the%20Difference.md) 24 | + MEDIUM 25 | * [Maximum Difference Between Node and Ancestor](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Medium/Maximum%20Difference%20Between%20Node%20and%20Ancestor.md) 26 | * [Add Two Numbers II](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Medium/Add%20Two%20Numbers%20II.md) 27 | * [Minimum Height Trees](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Medium/Minimum%20Height%20Trees.md) 28 | * [Insertion Sort List](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Medium/Insertion%20Sort%20List.md) 29 | * [Number of Longest Increasing Subsequence](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Medium/Number%20of%20Longest%20Increasing%20Subsequence.md) 30 | * [Maximize Distance to Closest Person](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Medium/Maximize%20Distance%20to%20Closest%20Person.md) 31 | * [Linked List Cycle II](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Medium/Linked%20List%20Cycle%20II.md) 32 | * [Champagne Tower](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Medium/Champagne%20Tower.md) 33 | * [Bag of Tokens](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Medium/Bag%20of%20Tokens.md) 34 | * [132 Pattern](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Medium/132%20Pattern.md) 35 | * [Asteroid Collision](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Medium/Asteroid%20Collision.md) 36 | * [Clone Graph](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Medium/Clone%20Graph.md) 37 | * [Minimum Domino Rotations For Equal Row](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Medium/Minimum%20Domino%20Rotations%20For%20Equal%20Row.md) 38 | * [Repeated DNA Sequences](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Medium/Repeated%20DNA%20Sequences.md) 39 | * [Search A 2D Matrix](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Medium/Search%20a%202D%20Matrix.md) 40 | * [Rotate Array](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Medium/Rotate%20Array.md) 41 | * [House Robber II](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Medium/House%20Robber%20II.md) 42 | * [Sort List](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Medium/Sort%20List.md) 43 | * [Remove Duplicate Letters](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Medium/Remove%20Duplicate%20Letters.md) 44 | * [Minimum Number of Arrows to Burst Balloons](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Medium/Minimum%20Number%20of%20Arrows%20to%20Burst%20Balloons.md) 45 | * [Rotate List](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Medium/Rotate%20List.md) 46 | * [Insert into Binary Search Tree](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Medium/Insert%20into%20a%20Binary%20Search%20Tree.md) 47 | * [Remove Covered Intervals](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Medium/Remove%20Covered%20Intervals.md) 48 | * [K Diff Pairs in Array](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Medium/K-diff%20Pairs%20in%20an%20Array.md) 49 | * [Combination Sum](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Medium/Combination%20Sum.md) 50 | * [Word Break](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Medium/Word%20Break.md) 51 | * [Subarray Product Less Than K](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Medium/Subarray%20Product%20Less%20Than%20K.md) 52 | * [Evaluate Division](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Medium/Evaluate%20Division.md) 53 | * [Teemo Attacking](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Medium/Teemo%20Attacking.md) 54 | * [Largest Number](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Medium/Largest%20Number.md) 55 | * [Gas Station](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Medium/Gas%20Station.md) 56 | * [Sequential Digits](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Medium/Sequential%20Digits.md) 57 | * [Car Pooling](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Medium/Car%20Pooling.md) 58 | * [Majority Element II](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Medium/Majority%20Element%20II.md) 59 | + HARD 60 | * [Recover Binary Search Tree](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Hard/Recover%20Binary%20Search%20Tree.md) 61 | * [Stone Game IV](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Hard/Stone%20Game%20IV.md) 62 | * [Best Time to Buy and Sell Stock IV](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Hard/Best%20Time%20to%20Buy%20and%20Sell%20Stock%20IV.md) 63 | * [First Missing Positive](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Hard/First%20Missing%20Positive.md) 64 | * [Unique Paths III](https://github.com/VikasViki/Competitive_Programming/blob/master/LeetCode/Hard/Unique%20Paths%20III.md) 65 | 66 | - [InterviewBit](https://www.interviewbit.com/profile/vikasviki) 67 | + Day 2: Array and Math 68 | * Assignment 69 | - [Closest MinMax](https://github.com/VikasViki/Competitive_Programming/blob/master/InterviewBit/Day%202:%20Array%20and%20Math/Assignment/Closest%20MinMax) 70 | + Day 3 71 | * HomeWork 72 | - [Alternate positive and negative elements (Using Extra Space)](https://github.com/VikasViki/Competitive_Programming/blob/master/InterviewBit/Day-3/HomeWork/Alternate%20positive%20and%20negative%20elements%20(Using%20Extra%20Space)) 73 | + Day 6 74 | * Assignment 75 | - [Greatest Common Divisor](https://github.com/VikasViki/Competitive_Programming/blob/master/InterviewBit/Day%206/Assignment/Greatest%20Common%20Divisor) 76 | - [Delete One](https://github.com/VikasViki/Competitive_Programming/blob/master/InterviewBit/Day%206/Assignment/Delete%20one) 77 | - [Pubg](https://github.com/VikasViki/Competitive_Programming/blob/master/InterviewBit/Day%206/Assignment/Pubg) 78 | - [Divisor Game](https://github.com/VikasViki/Competitive_Programming/blob/master/InterviewBit/Day%206/Assignment/Divisor%20Game) 79 | - [Delete Elements](https://github.com/VikasViki/Competitive_Programming/blob/master/InterviewBit/Day%206/Assignment/Delete%20Elements) 80 | * Homework 81 | - [Trailing Zeros in Factorial](https://github.com/VikasViki/Competitive_Programming/blob/master/InterviewBit/Day%206/Homework/Trailing%20Zeros%20in%20Factorial) 82 | - [Enumerating GCD](https://github.com/VikasViki/Competitive_Programming/blob/master/InterviewBit/Day%206/Homework/Enumerating%20GCD) 83 | - [A, B and Modulo](https://github.com/VikasViki/Competitive_Programming/blob/master/InterviewBit/Day%206/Homework/A%2C%20B%20and%20Modulo) 84 | - [Consecutive Number Sum](https://github.com/VikasViki/Competitive_Programming/blob/master/InterviewBit/Day%206/Homework/Consecutive%20Number%20Sum) 85 | + Day 8 86 | * Assignment 87 | - [Count of divisors for multiple queries](https://github.com/VikasViki/Competitive_Programming/blob/master/InterviewBit/Day%208/Assignment/Count%20of%20divisors%20for%20multiple%20queries) 88 | - [Factorial Array](https://github.com/VikasViki/Competitive_Programming/blob/master/InterviewBit/Day%208/Assignment/Factorial%20Array) 89 | * Homework 90 | - [Prime Sum](https://github.com/VikasViki/Competitive_Programming/blob/master/InterviewBit/Day%208/Homework/Prime%20Sum) 91 | - [Lucky Numbers](https://github.com/VikasViki/Competitive_Programming/blob/master/InterviewBit/Day%208/Homework/Lucky%20Numbers) 92 | - [Find nth Magic Number](https://github.com/VikasViki/Competitive_Programming/blob/master/InterviewBit/Day%208/Homework/Find%20nth%20Magic%20%20Number) 93 | + Day 17 - Two Pointers 94 | * Assignment 95 | - [Count of pairs with the given sum](https://github.com/VikasViki/Competitive_Programming/blob/master/InterviewBit/Day%2017%20:%20Two%20Pointers/Assignment/Count%20of%20pairs%20with%20the%20given%20sum) 96 | 97 | - [Codechef](https://www.codechef.com/users/vikasviki) 98 | + Long Challenge's 99 | * FEB19 100 | - [HMAPPY2](https://github.com/VikasViki/Competitive_Programming/blob/master/Codechef/Long_Challenge/FEB19/HMAPPY2.py) 101 | - [CHEFING](https://github.com/VikasViki/Competitive_Programming/blob/master/Codechef/Long_Challenge/FEB19/CHEFING.py) 102 | * MAR19 103 | - [CHNUM](https://github.com/VikasViki/Competitive_Programming/blob/master/Codechef/Long_Challenge/MAR19/CHNUM.py) 104 | + Cook Off's 105 | * FEB19 106 | - [TABLET](https://github.com/VikasViki/Competitive_Programming/blob/master/Codechef/Cook-Off/FEB19/TABLET.py) 107 | - [CHFPARTY](https://github.com/VikasViki/Competitive_Programming/blob/master/Codechef/Cook-Off/FEB19/CHFPARTY.py) 108 | * MAR19 109 | - [NBONACCI](https://github.com/VikasViki/Competitive_Programming/blob/master/Codechef/Cook-Off/MAR19/NBONACCI.py) 110 | + Lunch Time's 111 | * FEB19 112 | - [AVG](https://github.com/VikasViki/Competitive_Programming/blob/master/Codechef/Lunch_Time/FEB19/AVG.py) 113 | + Practice 114 | * BEGINNER 115 | * EASY 116 | * MEDIUM 117 | * HARD 118 | 119 | - Hacker Rank 120 | - [Geeks For Geeks](https://auth.geeksforgeeks.org/user/VikasViki/) 121 | + SCHOOL 122 | * [Reverse an Array](https://github.com/VikasViki/Competitive_Programming/blob/master/Geeks%20For%20Geeks/SCHOOL/Reverse%20an%20Array.py) 123 | * [Print alternate elements of an array](https://github.com/VikasViki/Competitive_Programming/blob/master/Geeks%20For%20Geeks/SCHOOL/Print%20alternate%20elements%20of%20an%20array.py) 124 | + BASIC 125 | * [Search an Element in an array](https://github.com/VikasViki/Competitive_Programming/blob/master/Geeks%20For%20Geeks/BASIC/Search%20an%20Element%20in%20an%20array.py) 126 | * [Rotating an Array](https://github.com/VikasViki/Competitive_Programming/blob/master/Geeks%20For%20Geeks/BASIC/Rotating%20an%20Array.py) 127 | * [Sort in specific order](https://github.com/VikasViki/Competitive_Programming/blob/master/Geeks%20For%20Geeks/BASIC/Sort%20in%20specific%20order.py) 128 | * [Find second largest element](https://github.com/VikasViki/Competitive_Programming/blob/master/Geeks%20For%20Geeks/BASIC/Find%20second%20largest%20element.py) 129 | * [Repeated I.Ds](https://github.com/VikasViki/Competitive_Programming/blob/master/Geeks%20For%20Geeks/BASIC/Repeated%20I.Ds.py) 130 | * [Multiply left and right array sum](https://github.com/VikasViki/Competitive_Programming/blob/master/Geeks%20For%20Geeks/BASIC/Multiply%20left%20and%20right%20array%20sum.py) 131 | * [Immediate Smaller Element](https://github.com/VikasViki/Competitive_Programming/blob/master/Geeks%20For%20Geeks/BASIC/Immediate%20Smaller%20Element.py) 132 | * [Reverse array in groups](https://github.com/VikasViki/Competitive_Programming/blob/master/Geeks%20For%20Geeks/BASIC/Reverse%20array%20in%20groups.py) 133 | * [Print an array in Pendulum Arrangement](https://github.com/VikasViki/Competitive_Programming/blob/master/Geeks%20For%20Geeks/BASIC/Print%20an%20array%20in%20Pendulum%20Arrangement.py) 134 | * [Transform to prime](https://github.com/VikasViki/Competitive_Programming/blob/master/Geeks%20For%20Geeks/BASIC/Transform%20to%20prime.py) 135 | * [Find the closest number](https://github.com/VikasViki/Competitive_Programming/blob/master/Geeks%20For%20Geeks/BASIC/Find%20the%20closest%20number.py) 136 | * [Count nodes of linked list](https://github.com/VikasViki/Competitive_Programming/blob/master/Geeks%20For%20Geeks/BASIC/Count%20nodes%20of%20linked%20list.py) 137 | * [Product of array elements](https://github.com/VikasViki/Competitive_Programming/blob/master/Geeks%20For%20Geeks/BASIC/Product%20of%20array%20elements.py) 138 | * [Start Coding - Python](https://github.com/VikasViki/Competitive_Programming/blob/master/Geeks%20For%20Geeks/BASIC/Start%20Coding%20-%20Python.py) 139 | * [Space Seperated - Python](https://github.com/VikasViki/Competitive_Programming/blob/master/Geeks%20For%20Geeks/BASIC/Space%20Seperated%20-%20Python.py) 140 | + EASY 141 | * [Sort an array of 0s, 1s and 2s](https://github.com/VikasViki/Competitive_Programming/blob/master/Geeks%20For%20Geeks/EASY/Sort%20an%20array%20of%200s%2C%201s%20and%202s.py) 142 | * [Chocolate Distribution Problem](https://github.com/VikasViki/Competitive_Programming/blob/master/Geeks%20For%20Geeks/EASY/Chocolate%20Distribution%20Problem.py) 143 | * [Index Of an Extra Element](https://github.com/VikasViki/Competitive_Programming/blob/master/Geeks%20For%20Geeks/EASY/Index%20Of%20an%20Extra%20Element.py) 144 | * [Leaders in an array](https://github.com/VikasViki/Competitive_Programming/blob/master/Geeks%20For%20Geeks/EASY/Leaders%20in%20an%20array.py) 145 | * [SP - Palindrome Family](https://github.com/VikasViki/Competitive_Programming/blob/master/Geeks%20For%20Geeks/EASY/SP%20-%20Palindrome%20Family.py) 146 | * [Sum of given range](https://github.com/VikasViki/Competitive_Programming/blob/master/Geeks%20For%20Geeks/EASY/Sum%20of%20given%20range.py) 147 | * [Triangular Number](https://github.com/VikasViki/Competitive_Programming/blob/master/Geeks%20For%20Geeks/EASY/Triangular%20Number.py) 148 | + MEDIUM 149 | * [Excel Sheet | Part - 1](https://github.com/VikasViki/Competitive_Programming/blob/master/Geeks%20For%20Geeks/MEDIUM/Excel%20Sheet%20%7C%20Part%20-%201.py) 150 | * [Sum of bit differences](https://github.com/VikasViki/Competitive_Programming/blob/master/Geeks%20For%20Geeks/MEDIUM/Sum%20of%20bit%20differences.py) 151 | * [Kth smallest element](https://github.com/VikasViki/Competitive_Programming/blob/master/Geeks%20For%20Geeks/MEDIUM/Kth%20smallest%20element.py) 152 | * [Multiply two strings](https://github.com/VikasViki/Competitive_Programming/blob/master/Geeks%20For%20Geeks/MEDIUM/Multiply%20two%20strings.py) 153 | * [Case-specific Sorting of Strings](https://github.com/VikasViki/Competitive_Programming/blob/master/Geeks%20For%20Geeks/MEDIUM/Case-specific%20Sorting%20of%20Strings.py) 154 | * [Find Prime numbers in a range](https://github.com/VikasViki/Competitive_Programming/blob/master/Geeks%20For%20Geeks/MEDIUM/Find%20Prime%20numbers%20in%20a%20range.py) 155 | * [Nearly Sorted Algorithm](https://github.com/VikasViki/Competitive_Programming/blob/master/Geeks%20For%20Geeks/MEDIUM/Nearly%20Sorted%20Algorithm.py) 156 | * [Subarray with given sum](https://github.com/VikasViki/Competitive_Programming/blob/master/Geeks%20For%20Geeks/EASY/Subarray%20with%20given%20sum.py) 157 | + HARD 158 | * [Return two prime numbers](https://github.com/VikasViki/Competitive_Programming/blob/master/Geeks%20For%20Geeks/HARD/Return%20two%20prime%20numbers.py) 159 | 160 | - Hacker Earth 161 | 162 | - CodeForces 163 | 164 | - Hacker Blocks 165 | + GENERAL 166 | * [Rotate Image](https://github.com/VikasViki/Competitive_Programming/blob/master/Hacker%20Blocks/GENERAL/Rotate%20Image) 167 | 168 | --------------------------------------------------------------------------------