├── Difficulty: Basic ├── Upper Case Conversion │ ├── upper-case-conversion.py │ └── README.md ├── Largest Element in Array │ ├── largest-element-in-array.py │ ├── largest-element-in-array.c │ ├── largest-element-in-array.cpp │ └── README.md ├── Odd or Even │ └── odd-or-even.cpp ├── Swap two numbers │ ├── swap-two-numbers.cpp │ └── README.md ├── Exceptionally odd │ └── exceptionally-odd.cpp ├── Rotate Array by One │ ├── rotate-array-by-one.py │ └── README.md ├── Sum of Array │ ├── sum-of-array.cpp │ └── README.md ├── Binary representation │ ├── binary-representation.cpp │ └── README.md ├── Array Subset │ └── array-subset.py ├── Triplet Family │ └── triplet-family.py ├── Count Linked List Nodes │ ├── count-linked-list-nodes.py │ └── README.md └── Java Switch Case statement │ └── java-switch-case-statement.cpp ├── Difficulty: Medium ├── Sort 0s, 1s and 2s │ └── sort-0s-1s-and-2s.py ├── Unique Number III │ └── unique-number-iii.cpp ├── Stock Buy and Sell – Multiple Transaction Allowed │ └── stock-buy-and-sell-multiple-transaction-allowed.cpp ├── Add Binary Strings │ ├── add-binary-strings.py │ └── README.md ├── Subsets │ └── subsets.cpp ├── Kth Smallest │ └── kth-smallest.py ├── Power Of Numbers │ └── power-of-numbers.py ├── Not a subset sum │ ├── not-a-subset-sum.py │ └── README.md ├── Search in Rotated Sorted Array │ └── search-in-rotated-sorted-array.py ├── Make array elements unique │ ├── make-array-elements-unique.py │ └── README.md ├── Count Subarrays with given XOR │ └── count-subarrays-with-given-xor.py ├── Nearly sorted │ ├── nearly-sorted.py │ └── README.md ├── Count the number of possible triangles │ └── count-the-number-of-possible-triangles.py ├── Container With Most Water │ └── container-with-most-water.py ├── Implement Pow │ ├── implement-pow.java │ └── README.md ├── Longest Subarray with Sum K │ └── longest-subarray-with-sum-k.py ├── Kth Missing Positive Number in a Sorted Array │ └── kth-missing-positive-number-in-a-sorted-array.py ├── Rotate Array │ └── rotate-array.py ├── Max sum in the configuration │ └── max-sum-in-the-configuration.py ├── Majority Element │ └── majority-element.py ├── Subarray range with given sum │ ├── subarray-range-with-given-sum.py │ └── README.md ├── Longest Common Subsequence │ └── longest-common-subsequence.py ├── Permutations of a String │ └── permutations-of-a-string.py ├── Meeting Rooms │ └── meeting-rooms.py ├── Next Permutation │ └── next-permutation.cpp ├── Rotate by 90 degree │ ├── rotate-by-90-degree.py │ └── README.md ├── Non-overlapping Intervals │ └── nonoverlapping-intervals.py ├── Kadane's Algorithm │ └── kadanes-algorithm.py ├── Print Anagrams Together │ └── print-anagrams-together.py ├── Count all triplets with given sum in sorted array │ └── count-all-triplets-with-given-sum-in-sorted-array.py ├── Minimum repeat to make substring │ └── minimum-repeat-to-make-substring.py ├── Longest Consecutive Subsequence │ ├── longest-consecutive-subsequence.py │ └── README.md ├── Majority Element II │ ├── majority-element-ii.py │ └── README.md ├── Maximum Product Subarray │ └── maximum-product-subarray.py ├── Next Greater Element │ └── next-greater-element.py ├── Aggressive Cows │ └── aggressive-cows.py ├── Overlapping Intervals │ ├── overlapping-intervals.py │ └── README.md ├── Spirally traversing a matrix │ └── spirally-traversing-a-matrix.py ├── Split array in three equal sum subarrays │ └── split-array-in-three-equal-sum-subarrays.py ├── Search in a sorted Matrix │ └── search-in-a-sorted-matrix.py ├── Minimize the Heights II │ └── minimize-the-heights-ii.py ├── Allocate Minimum Pages │ └── allocate-minimum-pages.py ├── Subarrays with sum K │ └── subarrays-with-sum-k.py ├── Smallest Positive Missing Number │ ├── smallest-positive-missing-number.cpp │ └── README.md ├── Find triplets with zero sum │ ├── find-triplets-with-zero-sum.py │ └── README.md ├── Minimize the Heights I │ └── minimize-the-heights-i.cpp ├── Minimum sum │ ├── minimum-sum.py │ └── README.md ├── Insert Interval │ └── insert-interval.py ├── Implement Atoi │ └── implement-atoi.java ├── Maximum path sum from any node │ └── README.md ├── k largest elements │ └── README.md ├── Quick Sort on Linked List │ └── README.md ├── Find All Triplets with Zero Sum │ └── find-all-triplets-with-zero-sum.cpp ├── Search Pattern (KMP-Algorithm) │ └── search-pattern-kmpalgorithm.py └── Merge two BST 's │ └── README.md ├── Difficulty: Easy ├── Number of 1 Bits │ ├── number-of-1-bits.py │ ├── number-of-1-bits.cpp │ └── README.md ├── Palindrome │ ├── palindrome.py │ └── README.md ├── Palindrome String │ └── palindrome-string.py ├── K-th Bit is Set or Not │ └── kth-bit-is-set-or-not.cpp ├── Binary Search │ ├── binary-search.py │ └── binary-search.cpp ├── Count the Zeros │ ├── count-the-zeros.py │ └── README.md ├── Check Equal Arrays │ ├── check-equal-arrays.py │ └── README.md ├── Reverse an Array │ └── reverse-an-array.py ├── Same characters in two strings │ └── same-characters-in-two-strings.py ├── Prime Number │ ├── prime-number.py │ └── README.md ├── Second Largest │ ├── second-largest.cpp │ ├── second-largest.py │ └── README.md ├── Power of 2 │ ├── power-of-2.cpp │ └── README.md ├── Missing in Array │ └── missing-in-array.py ├── Count Digits │ └── count-digits.py ├── Sorted and Rotated Minimum │ ├── sorted-and-rotated-minimum.py │ └── README.md ├── Number of occurrence │ ├── number-of-occurrence.py │ └── README.md ├── Nearest multiple of 10 │ └── nearest-multiple-of-10.py ├── Union of Arrays with Duplicates │ └── union-of-arrays-with-duplicates.py ├── Two Swaps │ └── two-swaps.py ├── Move All Zeroes to End │ ├── move-all-zeroes-to-end.py │ └── README.md ├── All divisors of a Number │ └── all-divisors-of-a-number.cpp ├── Single Number │ ├── single-number.py │ └── README.md ├── Two Smallests in Every Subarray │ └── two-smallests-in-every-subarray.py ├── Reorganize The Array │ ├── reorganize-the-array.py │ └── README.md ├── Anagram │ └── anagram.py ├── Pairs with difference k │ ├── pairs-with-difference-k.py │ └── README.md ├── Sort 0s, 1s and 2s │ ├── sort-0s-1s-and-2s.py │ └── README.md ├── Remove duplicates in array │ ├── remove-duplicates-in-array.py │ └── README.md ├── Union of Two Sorted Arrays with Distinct Elements │ └── union-of-two-sorted-arrays-with-distinct-elements.py ├── Kth distance │ └── kth-distance.py ├── Largest Pair Sum │ ├── largest-pair-sum.py │ └── README.md ├── Stock Buy and Sell – Max one Transaction Allowed │ └── stock-buy-and-sell-max-one-transaction-allowed.py ├── Two Sum - Pair with Given Sum │ └── two-sum-pair-with-given-sum.py ├── Largest subarray of 0's and 1's │ ├── largest-subarray-of-0s-and-1s.py │ └── README.md ├── Swap and Maximize │ └── swap-and-maximize.py ├── Equilibrium Point │ └── equilibrium-point.py ├── Longest substring with distinct characters │ ├── longest-substring-with-distinct-characters.py │ └── README.md ├── Strings Rotations of Each Other │ └── strings-rotations-of-each-other.py ├── Array Duplicates │ └── array-duplicates.py ├── Search in a Row-Column sorted matrix │ └── search-in-a-row-column-sorted-matrix.py ├── Rotate by 90 degree │ └── rotate-by-90-degree.py ├── Non Repeating Character │ └── non-repeating-character.py ├── Sum Pair closest to target │ └── sum-pair-closest-to-target.py ├── Pair with given sum in a sorted array │ └── pair-with-given-sum-in-a-sorted-array.cpp ├── Search in a row-wise sorted matrix │ ├── search-in-a-rowwise-sorted-matrix.py │ └── README.md ├── Occurence of an integer in a Linked List │ └── occurence-of-an-integer-in-a-linked-list.py ├── Max distance between same elements │ └── max-distance-between-same-elements.java ├── Sieve of Eratosthenes │ └── sieve-of-eratosthenes.cpp ├── Count pairs with given sum │ └── count-pairs-with-given-sum.cpp ├── Find the Sum of Last N nodes of the Linked List │ └── find-the-sum-of-last-n-nodes-of-the-linked-list.py ├── Split Linked List Alternatingly │ └── split-linked-list-alternatingly.py ├── Reverse a linked list │ └── reverse-a-linked-list.py ├── Find All Triplets with Zero Sum │ └── find-all-triplets-with-zero-sum.py ├── Intersection of Two arrays with Duplicate Elements │ └── intersection-of-two-arrays-with-duplicate-elements.cpp ├── Count distinct elements in every window │ └── count-distinct-elements-in-every-window.cpp └── Linked List Matrix │ └── linked-list-matrix.py └── Difficulty: Hard ├── Stock Buy and Sell – Multiple Transaction Allowed └── stock-buy-and-sell-multiple-transaction-allowed.py ├── Longest Prefix Suffix ├── longest-prefix-suffix.py └── README.md ├── Edit Distance └── edit-distance.py ├── Minimum Points To Reach Destination └── minimum-points-to-reach-destination.py ├── Longest repeating and non-overlapping substring └── longest-repeating-and-nonoverlapping-substring.py ├── Trapping Rain Water └── trapping-rain-water.py ├── Count Pairs in an Array └── count-pairs-in-an-array.py ├── Merge Without Extra Space └── merge-without-extra-space.py ├── Min Chars to Add for Palindrome ├── min-chars-to-add-for-palindrome.py └── README.md ├── Generalised Fibonacci numbers └── generalised-fibonacci-numbers.py ├── Histogram Max Rectangular Area └── histogram-max-rectangular-area.py ├── Max Circular Subarray Sum └── max-circular-subarray-sum.java ├── Find median in a stream └── find-median-in-a-stream.cpp ├── Count Smaller elements └── README.md └── N-Queen Problem └── nqueen-problem.py /Difficulty: Basic/Upper Case Conversion/upper-case-conversion.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | 3 | class Solution: 4 | def convert(self, s): 5 | return s.title() 6 | # code here -------------------------------------------------------------------------------- /Difficulty: Basic/Largest Element in Array/largest-element-in-array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def largest(self, arr): 3 | arr.sort() 4 | return arr[-1] 5 | # code here 6 | 7 | -------------------------------------------------------------------------------- /Difficulty: Medium/Sort 0s, 1s and 2s/sort-0s-1s-and-2s.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # Function to sort an array of 0s, 1s, and 2s 3 | def sort012(self, arr): 4 | # code here 5 | return arr.sort() 6 | -------------------------------------------------------------------------------- /Difficulty: Easy/Number of 1 Bits/number-of-1-bits.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | class Solution: 3 | def setBits(self, n): 4 | count = 0 5 | while(n): 6 | count+= n&1 7 | n>>=1 8 | return count 9 | # code here -------------------------------------------------------------------------------- /Difficulty: Easy/Palindrome/palindrome.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPalindrome(self, n): 3 | temp = str(n) 4 | if temp == temp[::-1]: 5 | return True 6 | else: 7 | return False 8 | 9 | # code here -------------------------------------------------------------------------------- /Difficulty: Basic/Odd or Even/odd-or-even.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isEven(int n) { 4 | // code here 5 | if(n&1!=0){ 6 | return false; 7 | }else{ 8 | return true; 9 | } 10 | } 11 | }; -------------------------------------------------------------------------------- /Difficulty: Easy/Palindrome String/palindrome-string.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | class Solution: 3 | def isPalindrome(self, s: str) -> bool: 4 | if s== s[::-1]: 5 | return True 6 | else: 7 | return False 8 | # code here -------------------------------------------------------------------------------- /Difficulty: Basic/Largest Element in Array/largest-element-in-array.c: -------------------------------------------------------------------------------- 1 | int largest(int arr[], int n) { 2 | // Code Here 3 | int res = arr[0]; 4 | for(int i=1;i res){ 6 | res = arr[i]; 7 | } 8 | } 9 | return res; 10 | } -------------------------------------------------------------------------------- /Difficulty: Easy/K-th Bit is Set or Not/kth-bit-is-set-or-not.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool checkKthBit(int n, int k) { 4 | // Your code here 5 | if((n&(1<0){ 6 | return true; 7 | } else{ 8 | return false; 9 | } 10 | } 11 | }; -------------------------------------------------------------------------------- /Difficulty: Easy/Binary Search/binary-search.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def binarysearch(self, arr, k): 3 | temp = set(arr) 4 | n=len(arr) 5 | for i in range(n): 6 | if k in temp: 7 | return arr.index(k) 8 | return -1 9 | 10 | # Code Here -------------------------------------------------------------------------------- /Difficulty: Basic/Swap two numbers/swap-two-numbers.cpp: -------------------------------------------------------------------------------- 1 | // User function Template for C++ 2 | 3 | class Solution { 4 | public: 5 | pair get(int a, int b) { 6 | // complete the function here 7 | a=a+b; 8 | b=a-b; 9 | a=a-b; 10 | return {a,b}; 11 | 12 | } 13 | }; -------------------------------------------------------------------------------- /Difficulty: Easy/Count the Zeros/count-the-zeros.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | 3 | class Solution: 4 | def countZeroes(self, arr): 5 | arr.sort() 6 | count=0 7 | for i in range(len(arr)): 8 | if(arr[i]==0): 9 | count+=1 10 | return count 11 | # code here -------------------------------------------------------------------------------- /Difficulty: Easy/Number of 1 Bits/number-of-1-bits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int setBits(int n) { 4 | // Write Your Code here 5 | int res = 0; 6 | while(n>0){ 7 | if(n&1!=0){ 8 | res++; 9 | } 10 | n=n/2; 11 | } 12 | return res; 13 | } 14 | }; -------------------------------------------------------------------------------- /Difficulty: Basic/Exceptionally odd/exceptionally-odd.cpp: -------------------------------------------------------------------------------- 1 | // User function template for C++ 2 | 3 | class Solution { 4 | public: 5 | int getOddOccurrence(int arr[], int n) { 6 | // code here 7 | int count =0; 8 | for(int i=0;i bool: 6 | a.sort() 7 | b.sort() 8 | #code here 9 | if a==b: 10 | return 1 11 | return 0 -------------------------------------------------------------------------------- /Difficulty: Basic/Rotate Array by One/rotate-array-by-one.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | class Solution: 4 | def rotate(self, arr: List[int]) -> List[int]: 5 | n = len(arr) 6 | temp = arr[n - 1] 7 | for i in range(n - 1, 0, -1): 8 | arr[i] = arr[i - 1] 9 | arr[0] = temp 10 | return arr 11 | -------------------------------------------------------------------------------- /Difficulty: Basic/Largest Element in Array/largest-element-in-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int largest(vector &arr) { 4 | // code here 5 | int num=arr[0]; 6 | int n=arr.size(); 7 | for(int i=1;i num){ 9 | num=arr[i]; 10 | } 11 | } 12 | return num; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Difficulty: Basic/Sum of Array/sum-of-array.cpp: -------------------------------------------------------------------------------- 1 | // User function template for C++ 2 | class Solution { 3 | public: 4 | // Function to return sum of elements 5 | int arraySum(vector& arr) { 6 | // code here 7 | int sum=0; 8 | int n=arr.size(); 9 | for(int i=0;i=0;i--){ 7 | if(n&(1< &arr) { 6 | // code here 7 | sort(arr.begin(),arr.end()); 8 | int n=arr.size(); 9 | int count=0; 10 | for(int i=0;i &arr) { 4 | // code here 5 | int lar=-1, res=-1; 6 | for(int i=0;i lar){ 8 | res=lar; 9 | lar=arr[i]; 10 | } else if(arr[i] < lar && arr[i]> res){ 11 | res=arr[i]; 12 | } 13 | } 14 | return res; 15 | } 16 | }; -------------------------------------------------------------------------------- /Difficulty: Easy/Power of 2/power-of-2.cpp: -------------------------------------------------------------------------------- 1 | // User function Template for C++ 2 | 3 | class Solution { 4 | public: 5 | // Function to check if given number n is a power of two. 6 | bool isPowerofTwo(int n) { 7 | // code here 8 | if(n==1){ 9 | return true; 10 | } 11 | while(n!=1){ 12 | if(n&1 !=0){ 13 | return false; 14 | } 15 | n=n/2; 16 | } 17 | return true; 18 | } 19 | }; -------------------------------------------------------------------------------- /Difficulty: Medium/Stock Buy and Sell – Multiple Transaction Allowed/stock-buy-and-sell-multiple-transaction-allowed.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public: 4 | int maximumProfit(vector &prices) { 5 | // code here 6 | int n=prices.size(); 7 | int count=0; 8 | for(int i=1;i prices[i-1]){ 10 | count+= prices[i]-prices[i-1]; 11 | } 12 | } 13 | return count; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Difficulty: Easy/Binary Search/binary-search.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int binarysearch(vector &arr, int k) { 4 | // code here 5 | int n=arr.size(); 6 | int low=0, high=n-1, res =-1; 7 | while(low<=high){ 8 | int mid = (low+high)/2; 9 | if(arr[mid]== k){ 10 | res =mid; 11 | high=mid-1; 12 | } else if(arr[mid] < k){ 13 | low = mid+1; 14 | } else{ 15 | high = mid-1; 16 | } 17 | } 18 | return res; 19 | } 20 | }; -------------------------------------------------------------------------------- /Difficulty: Medium/Add Binary Strings/add-binary-strings.py: -------------------------------------------------------------------------------- 1 | 2 | class Solution: 3 | def addBinary(self, A, B): 4 | # code here 5 | a=int(A,2) 6 | b=int(B,2) 7 | c=a+b 8 | return(bin(c)[2:]) 9 | 10 | #{ 11 | # Driver Code Starts 12 | #Initial Template for Python 3 13 | 14 | if __name__ == '__main__': 15 | T = int(input()) 16 | for i in range(T): 17 | a = input().strip() 18 | b = input().strip() 19 | ob = Solution() 20 | answer = ob.addBinary(a, b) 21 | 22 | print(answer) 23 | print("~") 24 | 25 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Easy/Missing in Array/missing-in-array.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | class Solution: 3 | 4 | # Note that the size of the array is n-1 5 | def missingNumber(self, n, arr): 6 | s = sum(arr) 7 | sn = (n*(n+1) )// 2 8 | missing = sn - s 9 | return missing 10 | 11 | # code here 12 | 13 | #{ 14 | # Driver Code Starts 15 | #Initial Template for Python 3 16 | 17 | t = int(input()) 18 | for _ in range(0, t): 19 | n = int(input()) 20 | arr = list(map(int, input().split())) 21 | s = Solution().missingNumber(n, arr) 22 | print(s) 23 | 24 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Subsets/subsets.cpp: -------------------------------------------------------------------------------- 1 | // User function Template for C++ 2 | 3 | class Solution { 4 | public: 5 | void bkt(int st, vector& arr,vector&v1, vector>&v){ 6 | v.push_back(v1); 7 | for(int i=st; i> subsets(vector& arr) { 14 | // code here 15 | sort(arr.begin(),arr.end()); 16 | vector>v; 17 | vectorv1; 18 | bkt(0,arr,v1,v); 19 | return v; 20 | } 21 | }; 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /Difficulty: Easy/Second Largest/second-largest.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | class Solution: 3 | def getSecondLargest(self, arr): 4 | temp = list(set(arr)) 5 | temp.sort() 6 | if len(temp) > 1: 7 | return temp[-2] 8 | return -1 9 | # Code Here 10 | 11 | 12 | #{ 13 | # Driver Code Starts 14 | # Initial Template for Python 3 15 | 16 | if __name__ == "__main__": 17 | t = int(input()) 18 | for _ in range(t): 19 | arr = list(map(int, input().split())) 20 | ob = Solution() 21 | ans = ob.getSecondLargest(arr) 22 | print(ans) 23 | print("~") 24 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Easy/Count Digits/count-digits.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | class Solution: 3 | def evenlyDivides (self, N): 4 | k=[int(d) for d in str(N)] 5 | b=[] 6 | for i in k: 7 | if i!=0: 8 | if N%i==0: 9 | b.append(i) 10 | else: 11 | None 12 | return len(b) 13 | 14 | #{ 15 | # Driver Code Starts 16 | #Initial Template for Python 3 17 | 18 | if __name__ == '__main__': 19 | t = int (input ()) 20 | for _ in range (t): 21 | N = int(input()) 22 | 23 | 24 | ob = Solution() 25 | print(ob.evenlyDivides(N)) 26 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Kth Smallest/kth-smallest.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | 3 | 4 | class Solution: 5 | 6 | def kthSmallest(self, arr,k): 7 | arr.sort() 8 | return arr[k-1] 9 | 10 | 11 | 12 | 13 | 14 | #{ 15 | # Driver Code Starts 16 | #Initial Template for Python 3 17 | 18 | #contributed by RavinderSinghPB 19 | if __name__ == '__main__': 20 | import random 21 | t = int(input()) 22 | for tcs in range(t): 23 | # n = int(input()) 24 | arr = list(map(int, input().strip().split())) 25 | k = int(input()) 26 | ob = Solution() 27 | print(ob.kthSmallest(arr, k)) 28 | 29 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Easy/Sorted and Rotated Minimum/sorted-and-rotated-minimum.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | 3 | class Solution: 4 | def findMin(self, arr): 5 | arr.sort() 6 | return arr[0] 7 | #complete the function here 8 | 9 | 10 | #{ 11 | # Driver Code Starts 12 | def main(): 13 | T = int(input()) 14 | 15 | while T > 0: 16 | a = list(map( 17 | int, 18 | input().strip().split())) # Convert input to list of integers 19 | print(Solution().findMin(a)) # Call findMin with the array 'a' 20 | T -= 1 21 | print("~") 22 | 23 | 24 | if __name__ == "__main__": 25 | main() 26 | 27 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Power Of Numbers/power-of-numbers.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | 3 | class Solution: 4 | #Complete this function 5 | def power(self,N,R): 6 | return pow(N,R,1000000007) 7 | #Your code here 8 | 9 | 10 | #{ 11 | # Driver Code Starts 12 | #Initial Template for Python 3 13 | 14 | import math 15 | 16 | def main(): 17 | 18 | T=int(input()) 19 | 20 | while(T>0): 21 | 22 | N=input() 23 | R=N[::-1] 24 | 25 | ob=Solution(); 26 | ans=ob.power(int(N),int(R)) 27 | print(ans) 28 | 29 | T-=1 30 | 31 | if __name__=="__main__": 32 | main() 33 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Not a subset sum/not-a-subset-sum.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | 3 | class Solution: 4 | def findSmallest(self, arr): 5 | num = 1 6 | for i in arr: 7 | if i > num: 8 | return num 9 | num = num + i 10 | return num 11 | 12 | 13 | #{ 14 | # Driver Code Starts 15 | #Initial Template for Python 3 16 | 17 | 18 | def main(): 19 | t = int(input()) 20 | for _ in range(t): 21 | arr = list(map(int, input().split())) 22 | ob = Solution() 23 | ans = ob.findSmallest(arr) 24 | print(ans) 25 | 26 | 27 | if __name__ == "__main__": 28 | main() 29 | 30 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Easy/Number of occurrence/number-of-occurrence.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | class Solution: 3 | def countFreq(self, arr, target): 4 | return arr.count(target) 5 | 6 | 7 | #code here 8 | 9 | 10 | #{ 11 | # Driver Code Starts 12 | #Initial Template for Python 3 13 | import bisect 14 | #Main 15 | if __name__ == '__main__': 16 | t = int(input()) 17 | while t: 18 | t -= 1 19 | A = [int(x) for x in input().strip().split()] 20 | nd = [int(x) for x in input().strip().split()] 21 | D = nd[0] 22 | ob = Solution() 23 | ans = ob.countFreq(A, D) 24 | print(ans) 25 | print("~") 26 | 27 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Easy/Nearest multiple of 10/nearest-multiple-of-10.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | sys.set_int_max_str_digits(100000) 3 | class Solution: 4 | def roundToNearest (self, string) : 5 | n=len(string) 6 | string=int(string) 7 | left=(string//10)*10 8 | right=(string//10+1)*10 9 | if string-left>right-string : 10 | res=str(right) 11 | else: 12 | res=str(left) 13 | return res.zfill(n) 14 | 15 | 16 | #{ 17 | # Driver Code Starts 18 | #Initial Template for Python 3 19 | for _ in range(0, int(input())): 20 | num_str = input() 21 | ob = Solution() 22 | res = ob.roundToNearest(num_str) 23 | print(res) 24 | 25 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Search in Rotated Sorted Array/search-in-rotated-sorted-array.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | 3 | class Solution: 4 | def search(self,arr,key): 5 | n = len(arr) 6 | for i in range(n): 7 | if key not in arr: 8 | return -1 9 | return arr.index(key) 10 | # Complete this function 11 | 12 | 13 | #{ 14 | # Driver Code Starts 15 | #Initial Template for Python 3 16 | 17 | if __name__ == '__main__': 18 | t = int(input()) 19 | 20 | for _ in range(t): 21 | A = list(map(int, input().strip().split())) 22 | k = int(input()) 23 | ob = Solution() 24 | print(ob.search(A, k)) 25 | print("~") 26 | 27 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Make array elements unique/make-array-elements-unique.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | 3 | class Solution: 4 | def minIncrements(self, arr): 5 | arr.sort() 6 | m , count = -1 , 0 7 | for e in arr: 8 | m = max(m+1 , e) 9 | count += m - e 10 | return count 11 | 12 | 13 | # Code here 14 | 15 | 16 | #{ 17 | # Driver Code Starts 18 | #Initial Template for Python 3 19 | 20 | if __name__ == '__main__': 21 | 22 | T = int(input()) 23 | while T > 0: 24 | arr = [int(i) for i in input().split()] 25 | ob = Solution() 26 | print(ob.minIncrements(arr)) 27 | 28 | T -= 1 29 | 30 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Easy/Union of Arrays with Duplicates/union-of-arrays-with-duplicates.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | 3 | class Solution: 4 | #Function to return the count of number of elements in union of two arrays. 5 | def findUnion(self, a, b): 6 | lis = list(set(a) | set(b)) 7 | return len(lis)# code here 8 | 9 | 10 | #{ 11 | # Driver Code Starts 12 | #Initial Template for Python 3 13 | 14 | if __name__ == '__main__': 15 | t = int(input()) 16 | for _ in range(t): 17 | 18 | a = [int(x) for x in input().strip().split()] 19 | b = [int(x) for x in input().strip().split()] 20 | ob = Solution() 21 | 22 | print(ob.findUnion(a, b)) 23 | print("~") 24 | 25 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Easy/Two Swaps/two-swaps.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def checkSorted(self, arr): 3 | #code here 4 | swaps = 0 5 | for i, e in enumerate(arr): 6 | while e-1 != i: 7 | t = arr[e-1] 8 | arr[e-1] = e 9 | e = t 10 | swaps += 1 11 | return swaps == 2 or swaps == 0 12 | 13 | 14 | #{ 15 | # Driver Code Starts 16 | if __name__ == "__main__": 17 | t = int(input().strip()) 18 | 19 | for _ in range(t): 20 | arr = list(map(int, input().split())) 21 | 22 | sol = Solution() 23 | result = sol.checkSorted(arr) 24 | if result: 25 | print("true") 26 | else: 27 | print("false") 28 | 29 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Hard/Stock Buy and Sell – Multiple Transaction Allowed/stock-buy-and-sell-multiple-transaction-allowed.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def maximumProfit(self, prices) -> int: 6 | n= len(prices) 7 | count = 0 8 | for i in range(1,n): 9 | if(prices[i] > prices[i-1]): 10 | count += prices[i]-prices[i-1] 11 | return count 12 | 13 | 14 | #{ 15 | # Driver Code Starts 16 | #Initial Template for Python 3 17 | if __name__ == "__main__": 18 | t = int(input()) 19 | for _ in range(t): 20 | arr = list(map(int, input().strip().split())) 21 | solution = Solution() 22 | res = solution.maximumProfit(arr) 23 | print(res) 24 | 25 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Easy/Move All Zeroes to End/move-all-zeroes-to-end.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | 3 | class Solution: 4 | def pushZerosToEnd(self,arr): 5 | n = len(arr) 6 | count = 0 7 | for i in range(n): 8 | if arr[i]!=0: 9 | arr[count],arr[i] = arr[i],arr[count] 10 | count += 1 11 | 12 | # code here 13 | 14 | 15 | #{ 16 | # Driver Code Starts 17 | #Initial Template for Python 3 18 | 19 | if __name__ == '__main__': 20 | tc = int(input()) 21 | while tc > 0: 22 | arr = list(map(int, input().strip().split())) 23 | ob = Solution() 24 | ob.pushZerosToEnd(arr) 25 | for x in arr: 26 | print(x, end=" ") 27 | print() 28 | tc -= 1 29 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Count Subarrays with given XOR/count-subarrays-with-given-xor.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def subarrayXor(self, arr, k): 3 | from collections import defaultdict 4 | prefix_xors = defaultdict(int, {0: 1}) 5 | curr_xor, count = 0, 0 6 | for a in arr: 7 | curr_xor ^= a 8 | count += prefix_xors[curr_xor ^ k] 9 | prefix_xors[curr_xor] += 1 10 | return count 11 | 12 | 13 | #{ 14 | # Driver Code Starts 15 | if __name__ == "__main__": 16 | tc = int(input()) 17 | 18 | for _ in range(tc): 19 | arr = list(map(int, input().split())) 20 | k = int(input()) 21 | 22 | obj = Solution() 23 | print(obj.subarrayXor(arr, k)) 24 | print("~") 25 | 26 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Easy/All divisors of a Number/all-divisors-of-a-number.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | // Initial Template for C++ 3 | #include 4 | using namespace std; 5 | 6 | // } Driver Code Ends 7 | 8 | class Solution { 9 | public: 10 | void print_divisors(int n) { 11 | // Code here. 12 | for(int i=1;i<=n;i++){ 13 | if(n%i==0){ 14 | cout<> T; 25 | while (T--) { 26 | int n; 27 | cin >> n; 28 | Solution ob; 29 | ob.print_divisors(n); 30 | cout << endl; 31 | 32 | cout << "~" << "\n"; 33 | } 34 | return 0; 35 | } 36 | // } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Easy/Single Number/single-number.py: -------------------------------------------------------------------------------- 1 | #{ 2 | # Driver Code Starts 3 | #Initial Template for Python 3 4 | 5 | # } Driver Code Ends 6 | #User function Template for python3 7 | 8 | class Solution: 9 | 10 | def getSingle(self,arr): 11 | ans = 0 12 | n = len(arr) 13 | for i in range(n): 14 | ans = ans ^ arr[i] 15 | return ans 16 | # code here 17 | 18 | 19 | #{ 20 | # Driver Code Starts. 21 | #Initial Template for Python 3 22 | 23 | if __name__ == "__main__": 24 | t = int(input()) 25 | while t > 0: 26 | # k= int(input()) 27 | arr = list(map(int, input().split())) 28 | ob = Solution() 29 | res = ob.getSingle(arr) 30 | print(res) 31 | t -= 1 32 | 33 | 34 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Easy/Two Smallests in Every Subarray/two-smallests-in-every-subarray.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def pairWithMaxSum(self, arr): 3 | n = len(arr) 4 | if n < 2: 5 | return -1 6 | ans = 0 7 | for i in range(1,n): 8 | ans = max(ans, sum(arr[i-1:i+1])) 9 | return ans 10 | #code here 11 | 12 | 13 | #{ 14 | # Driver Code Starts 15 | if __name__ == "__main__": 16 | import sys 17 | input = sys.stdin.read 18 | data = input().strip().split("\n") 19 | 20 | t = int(data[0]) 21 | lines = data[1:] 22 | 23 | for line in lines: 24 | s = list(map(int, line.strip().split())) 25 | solution = Solution() 26 | res = solution.pairWithMaxSum(s) 27 | print(res) 28 | 29 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Easy/Reorganize The Array/reorganize-the-array.py: -------------------------------------------------------------------------------- 1 | #{ 2 | # Driver Code Starts 3 | 4 | # } Driver Code Ends 5 | class Solution: 6 | def rearrange(self, arr): 7 | #Code here 8 | for i, e in enumerate(arr): 9 | while e != -1 and e != i: 10 | t = arr[e] 11 | arr[e] = e 12 | e = t 13 | arr[i] = e 14 | return arr 15 | 16 | #{ 17 | # Driver Code Starts. 18 | def main(): 19 | t = int(input()) 20 | for _ in range(t): 21 | input_str = input() 22 | arr = list(map(int, input_str.split())) 23 | solution = Solution() 24 | ans = solution.rearrange(arr) 25 | print(" ".join(map(str, ans))) 26 | 27 | if __name__ == "__main__": 28 | main() 29 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Easy/Anagram/anagram.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | from collections import Counter 3 | 4 | class Solution: 5 | 6 | #Function is to check whether two strings are anagram of each other or not. 7 | def areAnagrams(self, s1, s2): 8 | if Counter(s1) == Counter(s2): 9 | return True 10 | else: 11 | return False 12 | 13 | #code here 14 | 15 | 16 | #{ 17 | # Driver Code Starts 18 | #Initial Template for Python 3 19 | 20 | if __name__ == '__main__': 21 | t = int(input()) 22 | for i in range(t): 23 | a = input().strip() 24 | b = input().strip() 25 | if (Solution().areAnagrams(a, b)): 26 | print("true") 27 | else: 28 | print("false") 29 | print("~") 30 | 31 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Easy/Pairs with difference k/pairs-with-difference-k.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countPairsWithDiffK(self,arr, k): 3 | count = 0 4 | hashMap = {} 5 | for i in arr: 6 | hashMap[i] = hashMap.get(i, 0) + 1 7 | 8 | for number in arr: 9 | c = number + k 10 | if c in hashMap: 11 | count += hashMap[c] 12 | return count 13 | 14 | 15 | #{ 16 | # Driver Code Starts 17 | #Initial Template for Python 3 18 | 19 | if __name__ == '__main__': 20 | tc = int(input()) 21 | while tc > 0: 22 | arr = list(map(int, input().strip().split())) 23 | k = int(input().strip()) 24 | ob = Solution() 25 | ans = ob.countPairsWithDiffK(arr, k) 26 | print(ans) 27 | print("~") 28 | tc -= 1 29 | 30 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Hard/Longest Prefix Suffix/longest-prefix-suffix.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | 3 | class Solution: 4 | def lps(self, str): 5 | # code here 6 | n = len(str) 7 | lps = [0] * n 8 | length = 0 9 | for i in range(1,n): 10 | while length > 0 and str[i] != str[length] : 11 | length = lps[length - 1] 12 | if str[i] == str[length]: 13 | length += 1 14 | lps[i] = length 15 | return lps[-1] 16 | 17 | 18 | 19 | #{ 20 | # Driver Code Starts 21 | #Initial Template for Python 3 22 | 23 | if __name__ == '__main__': 24 | T = int(input()) 25 | for i in range(T): 26 | s = input() 27 | 28 | ob = Solution() 29 | answer = ob.lps(s) 30 | print(answer) 31 | 32 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Easy/Sort 0s, 1s and 2s/sort-0s-1s-and-2s.py: -------------------------------------------------------------------------------- 1 | #{ 2 | # Driver Code Starts 3 | 4 | # } Driver Code Ends 5 | class Solution: 6 | # Function to sort an array of 0s, 1s, and 2s 7 | def sort012(self, arr): 8 | arr.sort() 9 | # code here 10 | 11 | 12 | #{ 13 | # Driver Code Starts. 14 | def main(): 15 | t = int(input().strip()) # Read the number of test cases 16 | ob = Solution() 17 | 18 | while t > 0: 19 | t -= 1 20 | arr = list(map(int, 21 | input().strip().split()) 22 | ) # Read the array as space-separated integers 23 | ob.sort012(arr) # Sort the array 24 | 25 | print(' '.join(map(str, arr))) # Print the sorted array 26 | print("~") 27 | 28 | if __name__ == "__main__": 29 | main() 30 | 31 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Easy/Remove duplicates in array/remove-duplicates-in-array.py: -------------------------------------------------------------------------------- 1 | #{ 2 | # Driver Code Starts 3 | #Initial Template for Python 3 4 | 5 | # } Driver Code Ends 6 | class Solution: 7 | def removeDuplicates(self, arr): 8 | lis = [] 9 | seen = set() 10 | for num in arr: 11 | if num not in seen: 12 | lis.append(num) 13 | seen.add(num) 14 | return lis 15 | 16 | # code here 17 | 18 | 19 | #{ 20 | # Driver Code Starts. 21 | #Initial Template for Python 3 22 | 23 | if __name__ == "__main__": 24 | t = int(input()) 25 | while t > 0: 26 | arr = list(map(int, input().split())) 27 | ob = Solution() 28 | ans = ob.removeDuplicates(arr) 29 | print(*ans) 30 | print("~") 31 | t -= 1 32 | 33 | 34 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Nearly sorted/nearly-sorted.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class Solution: 4 | def nearlySorted(self, arr, k): 5 | import heapq 6 | hp=[] 7 | for ix,ve in enumerate(arr): 8 | heapq.heappush(hp,ve) 9 | if ix>=k: 10 | arr[ix-k]=heapq.heappop(hp) 11 | for ix in range(k): 12 | arr[-k+ix]=heapq.heappop(hp) 13 | 14 | #{ 15 | # Driver Code Starts 16 | # Initial Template for Python 3 17 | # Position this line where user code will be pasted. 18 | # Initial Template for Python 3 19 | 20 | if __name__ == "__main__": 21 | t = int(input()) 22 | while t > 0: 23 | arr = list(map(int, input().split())) 24 | k = int(input()) 25 | ob = Solution() 26 | ob.nearlySorted(arr, k) 27 | print(*arr) 28 | print("~") 29 | t -= 1 30 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Count the number of possible triangles/count-the-number-of-possible-triangles.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | 3 | class Solution: 4 | def countTriangles(self, arr): 5 | # code here 6 | from bisect import bisect_left 7 | arr.sort() 8 | ans, n = 0, len(arr) 9 | for i in range(n): 10 | for j in range(i+1, n): 11 | s = arr[i] + arr[j] 12 | k = bisect_left(arr, s, j+1) 13 | ans += k-j-1 14 | return ans 15 | 16 | #{ 17 | # Driver Code Starts 18 | #Initial Template for Python 3 19 | 20 | if __name__ == '__main__': 21 | t = int(input()) 22 | for _ in range(t): 23 | arr = list(map(int, input().strip().split())) 24 | ob = Solution() 25 | print(ob.countTriangles(arr)) 26 | 27 | print("~") 28 | 29 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Easy/Union of Two Sorted Arrays with Distinct Elements/union-of-two-sorted-arrays-with-distinct-elements.py: -------------------------------------------------------------------------------- 1 | #{ 2 | # Driver Code Starts 3 | #Initial Template for Python 3 4 | 5 | # } Driver Code Ends 6 | #User function Template for python3 7 | class Solution: 8 | #Function to return a list containing the union of the two arrays. 9 | def findUnion(self,a,b): 10 | return sorted(set(a+b)) 11 | # code here 12 | 13 | #{ 14 | # Driver Code Starts. 15 | if __name__ == '__main__': 16 | test_cases = int(input()) 17 | for cases in range(test_cases): 18 | a = list(map(int, input().strip().split())) 19 | b = list(map(int, input().strip().split())) 20 | ob = Solution() 21 | li = ob.findUnion(a, b) 22 | for val in li: 23 | print(val, end=' ') 24 | print() 25 | print("~") 26 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Container With Most Water/container-with-most-water.py: -------------------------------------------------------------------------------- 1 | 2 | class Solution: 3 | def maxWater(self, a): 4 | 5 | n = len(a) 6 | i, j = 0, n - 1 7 | ans = 0 8 | 9 | while i < j: 10 | ans = max(ans, min(a[j], a[i]) * (j - i)) 11 | if a[i] < a[j]: 12 | i += 1 13 | else: 14 | j -= 1 15 | 16 | return ans 17 | 18 | #{ 19 | # Driver Code Starts 20 | #Initial template for Python 3 21 | 22 | import math 23 | 24 | 25 | def main(): 26 | t = int(input()) 27 | while (t > 0): 28 | 29 | arr = [int(x) for x in input().strip().split()] 30 | obj = Solution() 31 | print(obj.maxWater(arr)) 32 | 33 | t -= 1 34 | print("~") 35 | 36 | 37 | if __name__ == "__main__": 38 | main() 39 | 40 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Hard/Edit Distance/edit-distance.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def editDistance(self, str1, str2): 3 | m=len(str1) 4 | n=len(str2) 5 | from functools import lru_cache 6 | @lru_cache(None) 7 | def dfs(i=m-1,j=n-1): 8 | nonlocal str1,str2 9 | if i<0 and j<0: 10 | return 0 11 | if i<0 or j<0: 12 | return max(i,j)+1 13 | if str1[i]==str2[j]: 14 | return dfs(i-1,j-1) 15 | return min(dfs(i-1,j),dfs(i,j-1),dfs(i-1,j-1))+1 16 | return dfs() 17 | # Code here 18 | 19 | 20 | #{ 21 | # Driver Code Starts 22 | if __name__ == '__main__': 23 | T = int(input()) 24 | for i in range(T): 25 | s, t = input().split() 26 | ob = Solution() 27 | ans = ob.editDistance(s, t) 28 | print(ans) 29 | 30 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Implement Pow/implement-pow.java: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | import java.io.*; 3 | import java.text.DecimalFormat; 4 | import java.util.*; 5 | 6 | public class Main { 7 | public static void main(String[] args) { 8 | Scanner sc = new Scanner(System.in); 9 | 10 | int t = sc.nextInt(); 11 | while (t-- > 0) { 12 | double b = sc.nextDouble(); 13 | int e = sc.nextInt(); 14 | Solution ob = new Solution(); 15 | System.out.printf("%.5f\n", ob.power(b, e)); 16 | System.out.println("~"); 17 | } 18 | sc.close(); 19 | } 20 | } 21 | 22 | 23 | // } Driver Code Ends 24 | // User function Template for Java 25 | class Solution { 26 | double power(double b, int e) { 27 | // code here 28 | return Math.pow(b,e); 29 | } 30 | } 31 | 32 | //{ Driver Code Starts. 33 | // } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Hard/Minimum Points To Reach Destination/minimum-points-to-reach-destination.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class Solution: 4 | def minPoints(self, m, n, points): 5 | j = [[float('inf') for _ in range(n+1)] for _ in range(m+1)] 6 | j[m-1][n]=1 7 | j[m][n-1]=1 8 | for i in range(m-1,-1,-1): 9 | for k in range(n-1,-1,-1): 10 | j[i][k]=max(1,(min(j[i+1][k],j[i][k+1])-points[i][k])) 11 | 12 | return j[0][0] 13 | #{ 14 | # Driver Code Starts 15 | #Initial Template for Python 3 16 | 17 | if __name__ == '__main__': 18 | T=int(input()) 19 | for i in range(T): 20 | m,n = input().split() 21 | m,n = int(m),int(n) 22 | points = [] 23 | for _ in range(m): 24 | temp = [int(x) for x in input().split()] 25 | points.append(temp) 26 | ob = Solution() 27 | ans = ob.minPoints(m,n,points) 28 | print(ans) 29 | 30 | 31 | 32 | 33 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Longest Subarray with Sum K/longest-subarray-with-sum-k.py: -------------------------------------------------------------------------------- 1 | # User function Template for python3 2 | 3 | class Solution: 4 | def longestSubarray(self, arr, k): 5 | # code here 6 | 7 | m = {0: -1} 8 | s, ans = 0, 0 9 | for i, e in enumerate(arr): 10 | s += arr[i] 11 | if s-k in m: 12 | ans = max(ans, i - m[s-k]) 13 | if s not in m: 14 | m[s] = i 15 | return ans 16 | 17 | 18 | 19 | 20 | #{ 21 | # Driver Code Starts 22 | #Initial Template for Python 3 23 | 24 | if __name__ == '__main__': 25 | tc = int(input().strip()) 26 | while tc > 0: 27 | arr = list(map(int, input().strip().split())) 28 | k = int(input().strip()) 29 | ob = Solution() 30 | print(ob.longestSubarray(arr, k)) 31 | tc -= 1 32 | print("~") 33 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Kth Missing Positive Number in a Sorted Array/kth-missing-positive-number-in-a-sorted-array.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | class Solution: 3 | def kthMissing(self, arr, k): 4 | s = set(arr) 5 | curr = 0 6 | count = 0 7 | while count < k: 8 | curr += 1 9 | if curr not in s: 10 | count += 1 11 | return curr 12 | 13 | # code here 14 | 15 | 16 | #{ 17 | # Driver Code Starts 18 | #Initial Template for Python 3 19 | 20 | #Main 21 | if __name__ == '__main__': 22 | t = int(input()) 23 | while t: 24 | t -= 1 25 | A = [int(x) for x in input().strip().split()] 26 | nd = [int(x) for x in input().strip().split()] 27 | D = nd[0] 28 | ob = Solution() 29 | ans = ob.kthMissing(A, D) 30 | print(ans) 31 | print("~") 32 | 33 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Easy/Kth distance/kth-distance.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | class Solution: 3 | def checkDuplicatesWithinK(self, arr, k): 4 | n = len(arr) 5 | for i in range(n-1): 6 | if(arr[i] in arr[i+1:i+k+1]): 7 | return True 8 | return False 9 | # your code 10 | 11 | 12 | #{ 13 | # Driver Code Starts 14 | # Initial Template for Python 3 15 | # Position this line where user code will be pasted. 16 | # Initial Template for Python 3 17 | 18 | if __name__ == "__main__": 19 | t = int(input()) 20 | while t > 0: 21 | arr = list(map(int, input().split())) 22 | k = int(input()) 23 | ob = Solution() 24 | res = ob.checkDuplicatesWithinK(arr, k) 25 | if res: 26 | print("true") 27 | else: 28 | print("false") 29 | # print(res) 30 | print("~") 31 | t -= 1 32 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Easy/Largest Pair Sum/largest-pair-sum.py: -------------------------------------------------------------------------------- 1 | 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | def pairsum(self, arr : List[int]) -> int: 7 | arr.sort() 8 | return arr[-1] + arr[-2] 9 | 10 | # code here 11 | 12 | 13 | 14 | 15 | #{ 16 | # Driver Code Starts 17 | class IntArray: 18 | 19 | def __init__(self) -> None: 20 | pass 21 | 22 | def Input(self, n): 23 | arr = [int(i) for i in input().strip().split()] #array input 24 | return arr 25 | 26 | def Print(self, arr): 27 | for i in arr: 28 | print(i, end=" ") 29 | print() 30 | 31 | 32 | if __name__ == "__main__": 33 | t = int(input()) 34 | for _ in range(t): 35 | 36 | arr = list(map(int, input().strip().split())) 37 | 38 | obj = Solution() 39 | res = obj.pairsum(arr) 40 | 41 | print(res) 42 | 43 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Basic/Array Subset/array-subset.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | 3 | class Solution: 4 | #Function to check if a is a subset of b. 5 | def isSubset(self, a, b): 6 | # Your code here 7 | return set(b).issubset(set(a)) 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | #{ 24 | # Driver Code Starts 25 | #Initial Template for Python 3 26 | 27 | 28 | def main(): 29 | 30 | T = int(input()) 31 | 32 | while (T > 0): 33 | a1 = [int(x) for x in input().strip().split()] 34 | a2 = [int(x) for x in input().strip().split()] 35 | ob = Solution() 36 | if ob.isSubset(a1, a2): 37 | print("Yes") 38 | else: 39 | print("No") 40 | 41 | T -= 1 42 | 43 | print("~") 44 | 45 | 46 | if __name__ == "__main__": 47 | main() 48 | 49 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Rotate Array/rotate-array.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | 3 | class Solution: 4 | def rotateArr(self, arr, d): 5 | #Your code here 6 | n = len(arr) 7 | arr.reverse() 8 | d %= n 9 | arr[:n-d] = reversed(arr[:n-d]) 10 | arr[n-d:] = reversed(arr[n-d:]) 11 | 12 | 13 | #{ 14 | # Driver Code Starts 15 | #Initial Template for Python 3 16 | 17 | import math 18 | 19 | 20 | def main(): 21 | T = int(input()) 22 | 23 | while (T > 0): 24 | A = [int(x) for x in input().strip().split()] 25 | nd = [int(x) for x in input().strip().split()] 26 | D = nd[0] 27 | ob = Solution() 28 | ob.rotateArr(A, D) 29 | 30 | for i in A: 31 | print(i, end=" ") 32 | 33 | print() 34 | 35 | T -= 1 36 | 37 | print("~") 38 | 39 | 40 | if __name__ == "__main__": 41 | main() 42 | 43 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Max sum in the configuration/max-sum-in-the-configuration.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | 3 | def max_sum(a,n): 4 | 5 | total=0 6 | sum1=0 7 | for i in range(n): 8 | sum1+=a[i]*i 9 | total+=a[i] 10 | j=n-1 11 | maxnum=sum1 12 | i=0 13 | while(j>0): 14 | if(i==0): 15 | sum1=sum1+(total-(a[0]+a[n-1]))-(a[j]*(n-1))+a[0] 16 | i+=1 17 | else: 18 | sum1=sum1+(total-(a[j]+a[j-1]))-(a[j-1]*(n-1))+a[j] 19 | j-=1 20 | if(sum1>maxnum): 21 | maxnum=sum1 22 | 23 | return maxnum 24 | 25 | 26 | #{ 27 | # Driver Code Starts 28 | #Initial Template for Python 3 29 | 30 | if __name__ == '__main__': 31 | t = int(input()) 32 | for i in range(t): 33 | n = int(input()) 34 | arr = list(map(int, input().strip().split())) 35 | print(max_sum(arr, n)) 36 | 37 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Easy/Stock Buy and Sell – Max one Transaction Allowed/stock-buy-and-sell-max-one-transaction-allowed.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maximumProfit(self, prices): 3 | n = len(prices) 4 | if n < 2: 5 | return 0 6 | ans = 0 7 | run = 0 8 | for i in range(1,n): 9 | run = max(0,run + prices[i] - prices[i-1]) 10 | ans = max(ans , run) 11 | return ans 12 | # code here 13 | 14 | 15 | #{ 16 | # Driver Code Starts 17 | if __name__ == "__main__": 18 | t = int(input()) # Read number of test cases 19 | for _ in range(t): 20 | # Read input and split it into a list of integers 21 | prices = list(map(int, input().split())) 22 | # Create a Solution object and calculate the result 23 | obj = Solution() 24 | result = obj.maximumProfit(prices) 25 | # Print the result 26 | print(result) 27 | 28 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Basic/Triplet Family/triplet-family.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findTriplet(self, arr): 3 | arr.sort() 4 | n = len(arr) 5 | for i in range(n): 6 | for j in range(n): 7 | res = arr[i] + arr[j] 8 | if i!=j and res in arr and res!=arr[i] and res!=arr[j]: 9 | return True 10 | return False 11 | 12 | 13 | #{ 14 | # Driver Code Starts 15 | #Initial Template for Python 3 16 | # Position this line where user code will be pasted. 17 | #Initial Template for Python 3 18 | 19 | if __name__ == "__main__": 20 | t = int(input()) 21 | while t > 0: 22 | arr = list(map(int, input().split())) 23 | ob = Solution() 24 | res = ob.findTriplet(arr) 25 | if (res): 26 | print("true") 27 | else: 28 | print("false") 29 | # print(res) 30 | print("~") 31 | t -= 1 32 | 33 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Easy/Two Sum - Pair with Given Sum/two-sum-pair-with-given-sum.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | class Solution: 3 | def twoSum(self, arr, target): 4 | temp = dict() 5 | n = len(arr) 6 | for i in range(n): 7 | ans = target - arr[i] 8 | if ans in temp: 9 | return True 10 | temp[arr[i]] = i 11 | return False 12 | 13 | 14 | #{ 15 | # Driver Code Starts 16 | #Initial Template for Python 3 17 | 18 | #Initial Template for Python 3 19 | 20 | 21 | def main(): 22 | T = int(input()) 23 | while T > 0: 24 | x = int(input()) 25 | arr = list(map(int, input().strip().split())) 26 | ob = Solution() 27 | ans = ob.twoSum(arr, x) 28 | if ans: 29 | print("true") 30 | else: 31 | print("false") 32 | T -= 1 33 | print("~") 34 | 35 | 36 | if __name__ == "__main__": 37 | main() 38 | 39 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Hard/Longest repeating and non-overlapping substring/longest-repeating-and-nonoverlapping-substring.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | 3 | class Solution: 4 | def longestSubstring(self, s , n): 5 | # code here 6 | 7 | 8 | 9 | ln = len(s) 10 | 11 | res = "-1" 12 | 13 | l = 0 14 | 15 | r = 0 16 | 17 | for r in range(ln): 18 | 19 | substr = s[l:r+1] 20 | 21 | if s.find(substr, r+1) != -1: 22 | 23 | res = substr 24 | 25 | else: 26 | 27 | l+=1 28 | 29 | 30 | return res 31 | 32 | #{ 33 | # Driver Code Starts 34 | #Initial Template for Python 3 35 | 36 | if __name__ == '__main__': 37 | t = int (input ()) 38 | for _ in range (t): 39 | N=int(input()) 40 | S=input() 41 | 42 | ob = Solution() 43 | print(ob.longestSubstring(S , N)) 44 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Majority Element/majority-element.py: -------------------------------------------------------------------------------- 1 | #User function template for Python 3 2 | 3 | class Solution: 4 | def majorityElement(self, arr): 5 | #Your code here 6 | candidate, count = None, 0 7 | for num in arr: 8 | if count == 0: 9 | candidate, count = num, 1 10 | elif num == candidate: 11 | count += 1 12 | else: 13 | count -= 1 14 | return candidate if arr.count(candidate) > len(arr) // 2 else -1 15 | 16 | #{ 17 | # Driver Code Starts 18 | #Initial Template for Python 3 19 | 20 | import math 21 | 22 | from sys import stdin 23 | 24 | 25 | def main(): 26 | T = int(input()) 27 | while (T > 0): 28 | 29 | A = [int(x) for x in input().strip().split()] 30 | 31 | obj = Solution() 32 | print(obj.majorityElement(A)) 33 | 34 | T -= 1 35 | 36 | 37 | if __name__ == "__main__": 38 | main() 39 | 40 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Hard/Trapping Rain Water/trapping-rain-water.py: -------------------------------------------------------------------------------- 1 | 2 | class Solution: 3 | def maxWater(self, arr): 4 | # code here 5 | n = len(arr) 6 | left, right = [0]*n, [0]*n 7 | m1, m2 = 0, 0 8 | for i in range(n): 9 | m1 = max(m1, arr[i]) 10 | left[i] = m1 11 | m2 = max(m2, arr[n-1-i]) 12 | right[n-1-i] = m2 13 | 14 | ans = 0 15 | for i in range(n): 16 | ans += min(left[i], right[i]) - arr[i] 17 | return ans 18 | 19 | 20 | #{ 21 | # Driver Code Starts 22 | #Initial template for Python 3 23 | 24 | import math 25 | 26 | 27 | def main(): 28 | t = int(input()) 29 | while (t > 0): 30 | 31 | arr = [int(x) for x in input().strip().split()] 32 | obj = Solution() 33 | print(obj.maxWater(arr)) 34 | 35 | t -= 1 36 | print("~") 37 | 38 | 39 | if __name__ == "__main__": 40 | main() 41 | 42 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Subarray range with given sum/subarray-range-with-given-sum.py: -------------------------------------------------------------------------------- 1 | #{ 2 | # Driver Code Starts 3 | #Initial Template for Python 3 4 | 5 | # } Driver Code Ends 6 | #User function Template for python3 7 | 8 | class Solution: 9 | def subArraySum(self,arr, target): 10 | ans = ssum = 0 11 | d = dict() 12 | d[0] = 1 13 | for idx, item in enumerate(arr): 14 | ssum += item 15 | if ssum - target in d: 16 | ans += d[ssum - target] 17 | d[ssum] = d.get(ssum, 0) + 1 18 | return ans 19 | 20 | #{ 21 | # Driver Code Starts. 22 | #Initial Template for Python 3 23 | 24 | if __name__ == "__main__": 25 | t = int(input()) 26 | while t > 0: 27 | arr = list(map(int, input().split())) 28 | tar= int(input()) 29 | ob = Solution() 30 | res = ob.subArraySum(arr,tar) 31 | print(res) 32 | # print("~") 33 | t -= 1 34 | 35 | 36 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Hard/Count Pairs in an Array/count-pairs-in-an-array.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | 3 | class Solution: 4 | def countPairs(self,arr, n): 5 | import bisect 6 | tempArr = [] 7 | 8 | for i, num in enumerate(arr): 9 | tempArr.append(i*num) 10 | 11 | newArr = [] 12 | count= 0 13 | for num in tempArr: 14 | ind = bisect.bisect(newArr, num) 15 | count += (len(newArr) - ind) 16 | newArr.insert(ind, num) 17 | 18 | return count 19 | 20 | #{ 21 | # Driver Code Starts 22 | #Initial Template for Python 3 23 | 24 | def main(): 25 | 26 | T = int(input()) 27 | 28 | while(T > 0): 29 | n = int(input()) 30 | a = [int(x) for x in input().strip().split()] 31 | ob= Solution() 32 | print(ob.countPairs(a, n)) 33 | 34 | T -= 1 35 | 36 | 37 | if __name__ == "__main__": 38 | main() 39 | 40 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Longest Common Subsequence/longest-common-subsequence.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | 3 | class Solution: 4 | def lcs(self, n, m, str1, str2): 5 | dp=[[0 for _ in range(m+1)]for _ in range(n+1)] 6 | for i in range(1,n+1): 7 | for j in range(1,m+1): 8 | if str1[i-1]==str2[j-1]: 9 | dp[i][j]=1+dp[i-1][j-1] 10 | else: 11 | dp[i][j]=max(dp[i-1][j],dp[i][j-1]) 12 | return(dp[n][m]) 13 | 14 | #{ 15 | # Driver Code Starts 16 | #Initial Template for Python 3 17 | import atexit 18 | import io 19 | import sys 20 | 21 | # Contributed by : Nagendra Jha 22 | 23 | if __name__ == '__main__': 24 | test_cases = int(input()) 25 | for cases in range(test_cases): 26 | n, m = map(int, input().strip().split()) 27 | str1 = str(input()) 28 | str2 = str(input()) 29 | ob = Solution() 30 | print(ob.lcs(n, m, str1, str2)) 31 | 32 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Permutations of a String/permutations-of-a-string.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | 3 | class Solution: 4 | 5 | def permute(self, sl, s, i): 6 | s.add(''.join(sl)) 7 | for j in range(i, len(sl)): 8 | sl[i], sl[j] = sl[j], sl[i] 9 | self.permute(sl, s, i+1) 10 | sl[i], sl[j] = sl[j], sl[i] 11 | 12 | def findPermutation(self, s): 13 | # Code here 14 | sl = list(s) 15 | s = set() 16 | i = 0 17 | self.permute(sl, s, i) 18 | return list(s) 19 | 20 | 21 | 22 | 23 | #{ 24 | # Driver Code Starts 25 | #Initial Template for Python 3 26 | 27 | if __name__ == '__main__': 28 | t = int(input()) 29 | for i in range(t): 30 | S = input() 31 | ob = Solution() 32 | ans = ob.findPermutation(S) 33 | ans.sort() 34 | for i in ans: 35 | print(i, end=" ") 36 | print() 37 | print("~") 38 | 39 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Easy/Largest subarray of 0's and 1's/largest-subarray-of-0s-and-1s.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxLen(self, arr): 3 | max_len = 0 4 | cumsum = 0 5 | hashmap = {0: -1} # Initialize hashmap with cumsum 0 at index -1 6 | 7 | for i in range(len(arr)): 8 | # Increment or decrement cumsum based on the value 9 | cumsum += 1 if arr[i] == 1 else -1 10 | 11 | if cumsum in hashmap: 12 | # If the cumsum has been seen before, calculate the subarray length 13 | max_len = max(max_len, i - hashmap[cumsum]) 14 | else: 15 | # Store the first occurrence of this cumsum 16 | hashmap[cumsum] = i 17 | 18 | return max_len 19 | 20 | 21 | #{ 22 | # Driver Code Starts 23 | #Initial Template for Python 3 24 | 25 | t = int(input()) 26 | for _ in range(0, t): 27 | a = list(map(int, input().split())) 28 | s = Solution().maxLen(a) 29 | print(s) 30 | 31 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Meeting Rooms/meeting-rooms.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | class Solution: 3 | def canAttend(self,arr): 4 | n = len(arr) 5 | arr = sorted(arr) 6 | for i in range(n-1): 7 | if(arr[i][1] > arr[i+1][0]): 8 | return False 9 | return True 10 | # Your Code Here 11 | 12 | 13 | #{ 14 | # Driver Code Starts 15 | if __name__ == '__main__': 16 | T = int(input()) 17 | for i in range(T): 18 | n = int(input()) 19 | # a = list(map(int, input().strip().split())) 20 | arr = [] 21 | # j = 0 22 | for i in range(n): 23 | a = list(map(int, input().strip().split())) 24 | x = a[0] 25 | # j += 1 26 | y = a[1] 27 | # j += 1 28 | arr.append([x, y]) 29 | obj = Solution() 30 | ans = obj.canAttend(arr) 31 | if ans: 32 | print("true") 33 | else: 34 | print("false") 35 | 36 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Next Permutation/next-permutation.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | 6 | // } Driver Code Ends 7 | // User function Template for C++ 8 | 9 | class Solution { 10 | public: 11 | void nextPermutation(vector& arr) { 12 | next_permutation(arr.begin(),arr.end()); 13 | } 14 | }; 15 | 16 | 17 | 18 | 19 | //{ Driver Code Starts. 20 | int main() { 21 | int t; 22 | cin >> t; 23 | cin.ignore(); 24 | while (t--) { 25 | vector arr; 26 | string input; 27 | getline(cin, input); 28 | stringstream ss(input); 29 | int number; 30 | while (ss >> number) { 31 | arr.push_back(number); 32 | } 33 | Solution ob; 34 | int n = arr.size(); 35 | ob.nextPermutation(arr); 36 | for (int i = 0; i < n; i++) { 37 | cout << arr[i] << " "; 38 | } 39 | cout << "\n"; 40 | } 41 | return 0; 42 | } 43 | 44 | // } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Rotate by 90 degree/rotate-by-90-degree.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | def rotate(matrix): 3 | #code here 4 | 5 | n = len(matrix) 6 | def transpose(m): 7 | n = len(m) 8 | for i in range(n): 9 | for j in range(i+1, n): 10 | m[i][j], m[j][i] = m[j][i], m[i][j] 11 | 12 | transpose(matrix) 13 | for r in range(n): 14 | matrix[r].reverse() 15 | return matrix 16 | 17 | #{ 18 | # Driver Code Starts 19 | #Initial Template for Python 3 20 | 21 | if __name__ == '__main__': 22 | t = int(input()) 23 | for _ in range(t): 24 | N = int(input()) 25 | matrix = [] 26 | for i in range(N): 27 | arr = [int(x) for x in input().strip().split()] 28 | matrix.append(arr) 29 | 30 | rotate(matrix) 31 | for i in range(N): 32 | for j in range(N): 33 | print(matrix[i][j], end=' ') 34 | print() 35 | print("~") 36 | 37 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Non-overlapping Intervals/nonoverlapping-intervals.py: -------------------------------------------------------------------------------- 1 | #{ 2 | # Driver Code Starts 3 | #Initial Template for Python 3 4 | 5 | # } Driver Code Ends 6 | #User function Template for python3 7 | 8 | class Solution: 9 | def minRemoval(self, intervals): 10 | count = 0 11 | intervals.sort(key = lambda x:x[0]) 12 | n = len(intervals) 13 | end = intervals[0][1] 14 | for i in range(1,n): 15 | if intervals[i][0] < end: 16 | count += 1 17 | end = min(intervals[i][1] , end) 18 | else: 19 | end = intervals[i][1] 20 | return count 21 | # Code here 22 | 23 | #{ 24 | # Driver Code Starts. 25 | if __name__ == '__main__': 26 | t = int(input ()) 27 | for _ in range (t): 28 | N = int(input()) 29 | intervals = [list(map(int, input().split())) for i in range(N)] 30 | ob = Solution() 31 | res = ob.minRemoval(intervals) 32 | print(res) 33 | print("~") 34 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Easy/Swap and Maximize/swap-and-maximize.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | 3 | class Solution: 4 | def maxSum(self,arr): 5 | # code here 6 | ans=[] 7 | arr.sort() 8 | i=0 9 | n=len(arr) 10 | while len(ans) max_sum: 14 | max_sum = curr_sum 15 | if curr_sum < 0 : 16 | curr_sum = 0 17 | return(max_sum) 18 | ##Your code here 19 | 20 | #{ 21 | # Driver Code Starts 22 | #Initial Template for Python 3 23 | 24 | import math 25 | 26 | 27 | def main(): 28 | T = int(input()) 29 | while (T > 0): 30 | 31 | arr = [int(x) for x in input().strip().split()] 32 | 33 | ob = Solution() 34 | 35 | print(ob.maxSubArraySum(arr)) 36 | 37 | T -= 1 38 | 39 | 40 | if __name__ == "__main__": 41 | main() 42 | 43 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Print Anagrams Together/print-anagrams-together.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | 3 | from collections import defaultdict 4 | class Solution: 5 | 6 | def anagrams(self, arr): 7 | n = len(arr) 8 | res = [] 9 | mp = {} 10 | for i in range(n): 11 | s = arr[i] 12 | s = ''.join(sorted(s)) 13 | if s not in mp: 14 | mp[s] = len(res) 15 | res.append([]) 16 | res[mp[s]].append(arr[i]) 17 | return res 18 | 19 | 20 | #code here 21 | 22 | 23 | 24 | #{ 25 | # Driver Code Starts 26 | #Initial Template for Python 3 27 | if __name__ == '__main__': 28 | t = int(input()) 29 | for tcs in range(t): 30 | words = input().split() 31 | 32 | ob = Solution() 33 | ans = ob.anagrams(words) 34 | 35 | for grp in sorted(ans): 36 | for word in grp: 37 | print(word, end=' ') 38 | print() 39 | 40 | print("~") 41 | 42 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Easy/Equilibrium Point/equilibrium-point.py: -------------------------------------------------------------------------------- 1 | # User function Template for python3 2 | class Solution: 3 | #Function to find equilibrium point in the array. 4 | def findEquilibrium(self, arr): 5 | # code here 6 | n,curr=len(arr),0 7 | right=[0]*n 8 | 9 | for i in range(n-1,-1,-1): 10 | curr+=arr[i] 11 | right[i]=curr 12 | 13 | curr=arr[0] 14 | for i in range(1,n-1): 15 | if curr==right[i+1]: 16 | return i 17 | curr+=arr[i] 18 | 19 | return -1 20 | 21 | 22 | 23 | 24 | #{ 25 | # Driver Code Starts 26 | #Initial Template for Python 3 27 | import math 28 | 29 | 30 | def main(): 31 | T = int(input()) 32 | while (T > 0): 33 | 34 | arr = [int(x) for x in input().strip().split()] 35 | 36 | ob = Solution() 37 | 38 | print(ob.findEquilibrium(arr)) 39 | print("~") 40 | T -= 1 41 | 42 | 43 | if __name__ == "__main__": 44 | main() 45 | 46 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Easy/Longest substring with distinct characters/longest-substring-with-distinct-characters.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | 3 | class Solution: 4 | def longestUniqueSubstr(self, s): 5 | # code here 6 | from collections import Counter 7 | cnt = Counter() 8 | left, ans = 0, 0 9 | for r in range(len(s)): 10 | c = s[r] 11 | cnt[c] += 1 12 | while left <= r and cnt[c] > 1: 13 | lc = s[left] 14 | cnt[lc] -= 1 15 | if cnt[lc] == 0: 16 | cnt.pop(lc) 17 | left += 1 18 | ans = max(ans, len(cnt)) 19 | return ans 20 | 21 | 22 | #{ 23 | # Driver Code Starts 24 | #Initial Template for Python 3 25 | 26 | if __name__ == '__main__': 27 | 28 | t = int(input()) 29 | 30 | for _ in range(t): 31 | s = input() 32 | 33 | solObj = Solution() 34 | 35 | ans = solObj.longestUniqueSubstr(s) 36 | 37 | print(ans) 38 | 39 | print("~") 40 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Count all triplets with given sum in sorted array/count-all-triplets-with-given-sum-in-sorted-array.py: -------------------------------------------------------------------------------- 1 | 2 | class Solution: 3 | def countTriplets(self, arr, target): 4 | from collections import defaultdict 5 | m = defaultdict(int) 6 | for e in arr: 7 | m[e] += 1 8 | 9 | ans = 0 10 | for i in range(len(arr)): 11 | m[arr[i]] -= 1 #remove the current element 12 | for j in range(0, i): #traverse from 0 until to i(not included) because these element have been removed by the above line during their turn 13 | lookfor = target-arr[i]-arr[j] 14 | ans += m[lookfor] 15 | return ans 16 | 17 | 18 | #{ 19 | # Driver Code Starts 20 | if __name__ == "__main__": 21 | t = int(input()) 22 | for _ in range(t): 23 | arr = list(map(int, input().split())) 24 | target = int(input()) 25 | ob = Solution() 26 | ans = ob.countTriplets(arr, target) 27 | print(ans) 28 | print("~") 29 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Hard/Merge Without Extra Space/merge-without-extra-space.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def mergeArrays(self, a, b): 3 | i=len(a)-1 4 | j=0 5 | while i>=0 and jb[j]: 7 | a[i],b[j]=b[j],a[i] 8 | i-=1 9 | j+=1 10 | else: 11 | break 12 | a.sort() 13 | b.sort() 14 | 15 | 16 | #{ 17 | # Driver Code Starts 18 | # Input handling and main function 19 | if __name__ == "__main__": 20 | # Number of test cases 21 | t = int(input().strip()) 22 | 23 | for _ in range(t): 24 | # Input first array 25 | a = list(map(int, input().strip().split())) 26 | # Input second array 27 | b = list(map(int, input().strip().split())) 28 | 29 | # Create solution object and merge the arrays 30 | solution = Solution() 31 | solution.mergeArrays(a, b) 32 | 33 | # Output both arrays in the same line space-separated 34 | print(" ".join(map(str, a))) 35 | print(" ".join(map(str, b))) 36 | 37 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Minimum repeat to make substring/minimum-repeat-to-make-substring.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | 3 | class Solution: 4 | def minRepeats(self, s1, s2): 5 | ss1 = set(s1) 6 | ss2 = set(s2) 7 | 8 | for k in ss2: 9 | if k not in ss1: 10 | return -1 11 | 12 | count = 1 13 | c = len(s2) 14 | new_s1 = s1 15 | 16 | # rounds 17 | while len(new_s1) <= 2*c: 18 | if new_s1.find(s2) != -1: 19 | return count 20 | count += 1 21 | new_s1 += s1 22 | 23 | # one extra round 24 | if new_s1.find(s2) != -1: 25 | return count 26 | 27 | return -1 28 | 29 | 30 | #{ 31 | # Driver Code Starts 32 | #Initial Template for Python 3 33 | 34 | if __name__ == '__main__': 35 | t = int(input()) 36 | for _ in range(t): 37 | A = input() 38 | B = input() 39 | 40 | ob = Solution() 41 | print(ob.minRepeats(A, B)) 42 | 43 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Easy/Strings Rotations of Each Other/strings-rotations-of-each-other.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | 3 | class Solution: 4 | 5 | #Function to check if two strings are rotations of each other or not. 6 | def areRotations(self,s1,s2): 7 | #code here 8 | temp = s1 + s1 9 | if s2 in temp: 10 | return True 11 | else: 12 | return False 13 | 14 | #{ 15 | # Driver Code Starts 16 | #Initial Template for Python 3 17 | import atexit 18 | import io 19 | import sys 20 | 21 | _INPUT_LINES = sys.stdin.read().splitlines() 22 | input = iter(_INPUT_LINES).__next__ 23 | _OUTPUT_BUFFER = io.StringIO() 24 | sys.stdout = _OUTPUT_BUFFER 25 | 26 | 27 | @atexit.register 28 | def write(): 29 | sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) 30 | 31 | 32 | if __name__ == '__main__': 33 | t = int(input()) 34 | for i in range(t): 35 | s1 = str(input()) 36 | s2 = str(input()) 37 | if (Solution().areRotations(s1, s2)): 38 | print("true") 39 | else: 40 | print("false") 41 | 42 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Longest Consecutive Subsequence/longest-consecutive-subsequence.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | 3 | 4 | 5 | class Solution: 6 | def longestConsecutive(self,arr): 7 | arr=sorted(set(arr)) 8 | mx=lth=1 9 | prv=-float('inf') 10 | for ve in arr: 11 | if ve==prv+1: 12 | lth+=1 13 | mx=max(mx,lth) 14 | else: 15 | lth=1 16 | prv=ve 17 | return mx 18 | #{ 19 | # Driver Code Starts 20 | #Initial Template for Python 3 21 | 22 | import atexit 23 | import io 24 | import sys 25 | 26 | _INPUT_LINES = sys.stdin.read().splitlines() 27 | input = iter(_INPUT_LINES).__next__ 28 | _OUTPUT_BUFFER = io.StringIO() 29 | sys.stdout = _OUTPUT_BUFFER 30 | 31 | 32 | @atexit.register 33 | def write(): 34 | sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) 35 | 36 | 37 | if __name__ == '__main__': 38 | t = int(input()) 39 | for tt in range(t): 40 | a = list(map(int, input().strip().split())) 41 | print(Solution().longestConsecutive(a)) 42 | print("~") 43 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Basic/Sum of Array/README.md: -------------------------------------------------------------------------------- 1 |

Sum of Array

Difficulty Level : Difficulty: Basic


You are given an integer array arr[]. The task is to find the sum of it.

2 |

Examples:

3 |
Input: arr[] = [1, 2, 3, 4]
 4 | Output: 10
 5 | Explanation: 1 + 2 + 3 + 4 = 10.
 6 | 
7 |
Input: arr[] = [1, 3, 3]
 8 | Output: 7
 9 | Explanation: 1 + 3 + 3 = 7.
10 | 
11 |

Constraints:
1 <= arr.size <= 105
1 <= arr[i] <= 104


Topic Tags :
Arrays Data Structures  -------------------------------------------------------------------------------- /Difficulty: Hard/Min Chars to Add for Palindrome/min-chars-to-add-for-palindrome.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minChar(self, s): 3 | def computeLPS(s): 4 | n = len(s) 5 | lps = [0] * n 6 | length = 0 7 | i = 1 8 | while i < n: 9 | if s[i] == s[length]: 10 | length += 1 11 | lps[i] = length 12 | i += 1 13 | else: 14 | if length != 0: 15 | length = lps[length - 1] 16 | else: 17 | lps[i] = 0 18 | i += 1 19 | return lps 20 | rev_s = s[::-1] 21 | combined = s + '#' + rev_s 22 | lps = computeLPS(combined) 23 | return len(s) - lps[-1] 24 | 25 | 26 | #{ 27 | # Driver Code Starts 28 | #Initial Template for Python 3 29 | 30 | if __name__ == "__main__": 31 | for _ in range(int(input())): 32 | s = input() 33 | obj = Solution() 34 | ans = obj.minChar(s) 35 | print(ans) 36 | print("~") 37 | 38 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Easy/Array Duplicates/array-duplicates.py: -------------------------------------------------------------------------------- 1 | 2 | from typing import List 3 | 4 | 5 | class Solution: 6 | def duplicates(self, n : int, arr : List[int]) -> List[int]: 7 | # code here 8 | freq = [0] * n 9 | result = [] 10 | for num in arr: 11 | freq[num] += 1 12 | for i in range(n): 13 | if freq[i] > 1: 14 | result.append(i) 15 | return result if result else [-1] 16 | 17 | 18 | #{ 19 | # Driver Code Starts 20 | class IntArray: 21 | 22 | def __init__(self) -> None: 23 | pass 24 | 25 | def Input(self, n): 26 | arr = [int(i) for i in input().strip().split()] #array input 27 | return arr 28 | 29 | def Print(self, arr): 30 | for i in arr: 31 | print(i, end=" ") 32 | print() 33 | 34 | 35 | if __name__ == "__main__": 36 | t = int(input()) 37 | for _ in range(t): 38 | 39 | n = int(input()) 40 | 41 | arr = IntArray().Input(n) 42 | 43 | obj = Solution() 44 | res = obj.duplicates(n, arr) 45 | 46 | IntArray().Print(res) 47 | 48 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Majority Element II/majority-element-ii.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMajority(self, arr): 3 | dic = {} 4 | n = len(arr) 5 | 6 | # Counting occurrences of each element 7 | for i in arr: 8 | if i in dic: 9 | dic[i] += 1 10 | else: 11 | dic[i] = 1 12 | 13 | # Finding elements that appear more than n // 3 times 14 | ans = [] 15 | for i in dic: 16 | if dic[i] > n // 3: 17 | ans.append(i) 18 | 19 | ans.sort() # Sorting the result 20 | return ans 21 | 22 | 23 | #{ 24 | # Driver Code Starts 25 | #Initial Template for Python 3 26 | 27 | 28 | def main(): 29 | t = int(input().strip()) 30 | for _ in range(t): 31 | s = input().strip() 32 | nums = list(map(int, s.split())) 33 | ob = Solution() 34 | ans = ob.findMajority(nums) 35 | if not ans: 36 | print("[]") 37 | else: 38 | print(" ".join(map(str, ans))) 39 | 40 | 41 | if __name__ == "__main__": 42 | main() 43 | 44 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Maximum Product Subarray/maximum-product-subarray.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | class Solution: 3 | 4 | # Function to find maximum 5 | # product subarray 6 | def maxProduct(self,arr): 7 | n = len(arr) 8 | if n < 2: 9 | return arr[0] 10 | prefix_product = 1 11 | suffix_product = 1 12 | max_product = float('-inf') 13 | for i in range(n): 14 | if prefix_product == 0: 15 | prefix_product = 1 16 | if suffix_product == 0: 17 | suffix_product = 1 18 | prefix_product *= arr[i] 19 | suffix_product *= arr[n-1-i] 20 | max_product = max(max_product, prefix_product, suffix_product) 21 | return max_product 22 | # code here 23 | 24 | 25 | #{ 26 | # Driver Code Starts 27 | #Initial Template for Python 3 28 | 29 | if __name__ == '__main__': 30 | tc = int(input()) 31 | while tc > 0: 32 | arr = list(map(int, input().strip().split())) 33 | ob = Solution() 34 | ans = ob.maxProduct(arr) 35 | print(ans) 36 | tc -= 1 37 | 38 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Next Greater Element/next-greater-element.py: -------------------------------------------------------------------------------- 1 | # User function Template for python3 2 | 3 | class Solution: 4 | # Function to find the next greater element for each element of the array. 5 | def nextLargerElement(self, arr): 6 | res = [] 7 | stack = [] 8 | n = len(arr) 9 | for i in range(n-1,-1,-1): 10 | ele = arr[i] 11 | while stack and stack[-1] <= ele: 12 | stack.pop() 13 | res.append(stack[-1] if stack else -1) 14 | stack.append(ele) 15 | return res[::-1] 16 | # code here 17 | 18 | 19 | #{ 20 | # Driver Code Starts 21 | # Initial Template for Python 3 22 | 23 | t = int(input()) # number of test cases 24 | for _ in range(t): 25 | arr = list(map(int, input().split())) # input array 26 | s = Solution().nextLargerElement(arr) # find the next greater elements 27 | 28 | # Output formatting 29 | if s: 30 | print(" ".join(map(str, s))) # Print next greater elements 31 | else: 32 | print("[]") # Print empty list if no next greater element is found 33 | print("~") 34 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Aggressive Cows/aggressive-cows.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | 3 | 4 | class Solution: 5 | def aggressiveCows(self, stalls, k): 6 | stalls.sort() 7 | def ok(d, k): 8 | p = stalls[0] 9 | for i in range(1, len(stalls)): 10 | if abs(stalls[i] - p) >= d: 11 | p = stalls[i] 12 | k -= 1 13 | return k <= 0 14 | 15 | lo, hi = 1, stalls[-1] - stalls[0] 16 | while lo < hi: 17 | mi = lo+(hi-lo)//2 18 | if ok(mi, k-1): 19 | lo = mi+1 20 | else: 21 | hi = mi 22 | lo -= 1 23 | return lo 24 | 25 | 26 | 27 | #{ 28 | # Driver Code Starts 29 | #Initial Template for Python 3 30 | import bisect 31 | #Main 32 | if __name__ == '__main__': 33 | t = int(input()) 34 | while t: 35 | t -= 1 36 | A = [int(x) for x in input().strip().split()] 37 | nd = [int(x) for x in input().strip().split()] 38 | D = nd[0] 39 | ob = Solution() 40 | ans = ob.aggressiveCows(A, D) 41 | print(ans) 42 | print("~") 43 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Basic/Upper Case Conversion/README.md: -------------------------------------------------------------------------------- 1 |

Upper Case Conversion

Difficulty Level : Difficulty: Basic


Given a string s, convert the first letter of each word in the string to uppercase. 

2 |

Examples:

3 |
Input: s = "gEEKs"
4 | Output: "GEEKs"
5 |
Input: s = "i love programming"
6 | Output: "I Love Programming"
7 |

Constraints:
1 <= s.length() <= 104
Consists of lowercase alphabets and spaces to separate words

Company Tags :
Nagarro 

Topic Tags :
Strings Data Structures  -------------------------------------------------------------------------------- /Difficulty: Easy/Search in a Row-Column sorted matrix/search-in-a-row-column-sorted-matrix.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | class Solution: 3 | def matSearch(self, mat, x): 4 | n = len(mat) 5 | m = len(mat[0]) 6 | for i in range(n): 7 | for j in range(m): 8 | if mat[i][j] == x: 9 | return True 10 | return False 11 | 12 | # Complete this function 13 | 14 | 15 | #{ 16 | # Driver Code Starts 17 | # Initial Template for Python 3 18 | 19 | if __name__ == "__main__": 20 | import sys 21 | input = sys.stdin.read 22 | data = input().split() 23 | 24 | t = int(data[0]) 25 | index = 1 26 | for _ in range(t): 27 | r = int(data[index]) 28 | c = int(data[index + 1]) 29 | index += 2 30 | matrix = [] 31 | for i in range(r): 32 | row = list(map(int, data[index:index + c])) 33 | matrix.append(row) 34 | index += c 35 | x = int(data[index]) 36 | index += 1 37 | ob = Solution() 38 | if ob.matSearch(matrix, x): 39 | print("true") 40 | else: 41 | print("false") 42 | print("~") 43 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Basic/Count Linked List Nodes/count-linked-list-nodes.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | 3 | ''' 4 | 5 | #Linked list class 6 | class LinkedList: 7 | def __init__(self): 8 | self.head=None 9 | self.tail=None 10 | ''' 11 | class Solution: 12 | # Function to count nodes of a linked list. 13 | def getCount(self, head): 14 | count = 0 15 | while(head != None): 16 | count += 1 17 | head = head.next 18 | return count 19 | # code here 20 | 21 | 22 | #{ 23 | # Driver Code Starts 24 | #Initial Template for Python 3 25 | 26 | 27 | class Node: 28 | 29 | def __init__(self, data): 30 | self.data = data 31 | self.next = None 32 | 33 | 34 | if __name__ == "__main__": 35 | import sys 36 | input = sys.stdin.read 37 | data = input().split('\n') 38 | 39 | t = int(data[0]) 40 | for i in range(1, t + 1): 41 | arr = list(map(int, data[i].split())) 42 | head = Node(arr[0]) 43 | tail = head 44 | for value in arr[1:]: 45 | tail.next = Node(value) 46 | tail = tail.next 47 | ob = Solution() 48 | print(ob.getCount(head)) 49 | 50 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Basic/Rotate Array by One/README.md: -------------------------------------------------------------------------------- 1 |

Rotate Array by One

Difficulty Level : Difficulty: Basic


Given an array arr, rotate the array by one position in clockwise direction.

2 |

Examples:

3 |
Input: arr[] = [1, 2, 3, 4, 5]
4 | Output: [5, 1, 2, 3, 4]
Explanation: If we rotate arr by one position in clockwise 5 come to the front and remaining those are shifted to the end.
5 |
Input: arr[] = [9, 8, 7, 6, 4, 2, 1, 3]
6 | Output: [3, 9, 8, 7, 6, 4, 2, 1]
Explanation: After rotating clock-wise 3 comes in first position.
7 |

Constraints:
1<=arr.size()<=105
0<=arr[i]<=105


Topic Tags :
Arrays implementation  -------------------------------------------------------------------------------- /Difficulty: Easy/Rotate by 90 degree/rotate-by-90-degree.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | 3 | 4 | class Solution: 5 | 6 | #Function to rotate matrix anticlockwise by 90 degrees. 7 | def rotateby90(self, mat): 8 | m,n = len(mat),len(mat[0]) 9 | for i in range(m): 10 | for j in range(n): 11 | if i > j: 12 | mat[i][j],mat[j][i] = mat[j][i],mat[i][j] 13 | mat.reverse() 14 | # code here 15 | 16 | 17 | #{ 18 | # Driver Code Starts 19 | #Initial Template for Python 3 20 | 21 | if __name__ == '__main__': 22 | import sys 23 | input = sys.stdin.read 24 | data = input().split() 25 | 26 | t = int(data[0]) 27 | index = 1 28 | 29 | for _ in range(t): 30 | n = int(data[index]) 31 | index += 1 32 | matrix = [] 33 | for i in range(n): 34 | row = list(map(int, data[index:index + n])) 35 | matrix.append(row) 36 | index += n 37 | obj = Solution() 38 | obj.rotateby90(matrix) 39 | for i in range(n): 40 | for j in range(n): 41 | print(matrix[i][j], end=" ") 42 | print() 43 | 44 | print("~") 45 | 46 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Easy/Largest Pair Sum/README.md: -------------------------------------------------------------------------------- 1 |

Largest Pair Sum

Difficulty Level : Difficulty: Easy


Find the largest pair sum in an array of distinct integers.

2 |

Examples :

3 |
Input: arr[] = [12, 34, 10, 6, 40]
 4 | Output: 74
 5 | Explanation: Sum of 34 and 40 is the largest, i.e, 34 + 40 = 74.
6 |
Input: arr[] = [10, 20, 30]
 7 | Output: 50
 8 | Explanation: 20 + 30 = 50.
9 |

Expected Time Complexity: O(n)
Expected Auxiliary Space: O(1)

10 |

Constraints:
2 ≤ arr.size() ≤ 106
0 ≤ arr[i] ≤ 106


Topic Tags :
two-pointer-algorithm Arrays Searching  -------------------------------------------------------------------------------- /Difficulty: Easy/Non Repeating Character/non-repeating-character.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | 3 | class Solution: 4 | 5 | #Function to find the first non-repeating character in a string. 6 | def nonRepeatingChar(self,s): 7 | lis = [] 8 | for i in s: 9 | if i not in lis: 10 | lis.append(i) 11 | for i in lis: 12 | if s.count(i)==1: 13 | return i 14 | return -1 15 | #code here 16 | 17 | 18 | 19 | 20 | #{ 21 | # Driver Code Starts 22 | #Initial Template for Python 3 23 | 24 | import atexit 25 | import io 26 | import sys 27 | 28 | _INPUT_LINES = sys.stdin.read().splitlines() 29 | input = iter(_INPUT_LINES).__next__ 30 | _OUTPUT_BUFFER = io.StringIO() 31 | sys.stdout = _OUTPUT_BUFFER 32 | 33 | 34 | @atexit.register 35 | def write(): 36 | sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) 37 | 38 | 39 | if __name__ == '__main__': 40 | t = int(input()) 41 | for i in range(t): 42 | s = str(input()) 43 | obj = Solution() 44 | ans = obj.nonRepeatingChar(s) 45 | if (ans != '$'): 46 | print(ans) 47 | else: 48 | print(-1) 49 | 50 | print("~") 51 | 52 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Overlapping Intervals/overlapping-intervals.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def mergeOverlap(self, arr): 3 | arr.sort() 4 | output = [] 5 | curr_start, curr_end = arr[0] 6 | for start, end in arr: 7 | if start <= curr_end: 8 | curr_end = max(curr_end, end) 9 | else: 10 | output.append((curr_start, curr_end)) 11 | curr_start, curr_end = start, end 12 | output.append((curr_start, curr_end)) 13 | return output 14 | 15 | 16 | #{ 17 | # Driver Code Starts 18 | if __name__ == '__main__': 19 | T = int(input()) 20 | for i in range(T): 21 | n = int(input()) 22 | # a = list(map(int, input().strip().split())) 23 | arr = [] 24 | # j = 0 25 | for i in range(n): 26 | a = list(map(int, input().strip().split())) 27 | x = a[0] 28 | # j += 1 29 | y = a[1] 30 | # j += 1 31 | arr.append([x, y]) 32 | obj = Solution() 33 | ans = obj.mergeOverlap(arr) 34 | for i in ans: 35 | for j in i: 36 | print(j, end=" ") 37 | print() 38 | 39 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Spirally traversing a matrix/spirally-traversing-a-matrix.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def spirallyTraverse(self, matrix): 3 | m = len(matrix) 4 | n = len(matrix[0]) 5 | k = 2 * min(m, n) 6 | dx = [0, 1, 0, -1] 7 | dy = [1, 0, -1, 0] 8 | x, y = 0, -1 9 | res = [] 10 | for d in range(k): 11 | for i in range(n): 12 | x += dx[d % 4] 13 | y += dy[d % 4] 14 | res.append(matrix[x][y]) 15 | m, n = n, m - 1 16 | return res 17 | 18 | 19 | 20 | #{ 21 | # Driver Code Starts 22 | if __name__ == "__main__": 23 | import sys 24 | input = sys.stdin.read 25 | data = input().split() 26 | 27 | t = int(data[0]) 28 | index = 1 29 | for _ in range(t): 30 | r = int(data[index]) 31 | c = int(data[index + 1]) 32 | index += 2 33 | matrix = [] 34 | for i in range(r): 35 | row = list(map(int, data[index:index + c])) 36 | matrix.append(row) 37 | index += c 38 | 39 | solution = Solution() 40 | result = solution.spirallyTraverse(matrix) 41 | print(" ".join(map(str, result))) 42 | print("~") 43 | 44 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Basic/Swap two numbers/README.md: -------------------------------------------------------------------------------- 1 |

Swap two numbers

Difficulty Level : Difficulty: Basic


You are given two numbers a and b. Your task is to swap the given two numbers.

2 |

Note: Try to do it without a temporary variable.

3 |

Examples:

4 |
Input: a = 13, b = 9
 5 | Output: 9 13
 6 | Explanation: After swapping it becomes 9 and 13.
 7 | 
8 |
Input: a = 15, b = 8
 9 | Output: 8 15
10 | Explanation: after swapping it becomes 8 and 15.
11 |

Constraints:
1 ≤ a, b ≤ 106

Company Tags :
Samsung 

Topic Tags :
Mathematical Algorithms  -------------------------------------------------------------------------------- /Difficulty: Hard/Generalised Fibonacci numbers/generalised-fibonacci-numbers.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | class Solution: 3 | def multiply(self, A, B, m): 4 | size = len(A) 5 | result = [[0] * size for _ in range(size)] 6 | for i in range(size): 7 | for j in range(size): 8 | for k in range(size): 9 | result[i][j] += (A[i][k] % m) * (B[k][j] % m) 10 | result[i][j] %= m 11 | return result 12 | 13 | def genFibNum(self, a, b, c, n, m): 14 | if n <= 2: 15 | return 1 % m 16 | mat = [[a, b, 1], [1, 0, 0], [0, 0, 1]] 17 | res = [[1, 0, 0], [0, 1, 0], [0, 0, 1]] 18 | n -= 2 19 | while n > 0: 20 | if n & 1: 21 | res = self.multiply(res, mat, m) 22 | mat = self.multiply(mat, mat, m) 23 | n >>= 1 24 | return (res[0][0] + res[0][1] + c * res[0][2]) % m 25 | 26 | 27 | #{ 28 | # Driver Code Starts 29 | #Initial Template for Python 3 30 | 31 | if __name__ == '__main__': 32 | t = int (input ()) 33 | for _ in range (t): 34 | a,b,c,n,m=map(int,input().split()) 35 | 36 | ob = Solution() 37 | print(ob.genFibNum(a,b,c,n,m)) 38 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Split array in three equal sum subarrays/split-array-in-three-equal-sum-subarrays.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | class Solution: 3 | def findSplit(self, arr): 4 | 5 | if sum(arr) % 3: 6 | return [-1, -1] 7 | 8 | target = sum(arr) // 3 9 | part_visited = 0 10 | prefix_sum = 0 11 | first_part_ends_at = -1 12 | 13 | for i in range(len(arr)): 14 | prefix_sum += arr[i] 15 | 16 | if prefix_sum == target: 17 | part_visited += 1 18 | first_part_ends_at = i 19 | if prefix_sum == (2*target) and i != len(arr)-1 and part_visited: 20 | return [first_part_ends_at, i] 21 | 22 | return [-1, -1] 23 | 24 | 25 | #{ 26 | # Driver Code Starts 27 | # Initial Template for Python 3 28 | 29 | # Main 30 | if __name__ == '__main__': 31 | t = int(input()) 32 | while t: 33 | t -= 1 34 | arr = [int(x) for x in input().strip().split()] 35 | 36 | ob = Solution() 37 | result = ob.findSplit(arr) 38 | 39 | if result == [-1, -1]: 40 | print("false") 41 | else: 42 | print("true") 43 | print("~") 44 | 45 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Easy/Sum Pair closest to target/sum-pair-closest-to-target.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | class Solution: 3 | def sumClosest(self, arr, target): 4 | n = len(arr) 5 | arr.sort() 6 | res = [] 7 | mindiff = float('inf') 8 | left = 0 9 | right = n-1 10 | while left < right: 11 | curr_sum = arr[left] + arr[right] 12 | if abs(target - curr_sum) < mindiff: 13 | mindiff = abs(target -curr_sum) 14 | res = [arr[left],arr[right]] 15 | if curr_sum < target: 16 | left += 1 17 | elif curr_sum > target: 18 | right -= 1 19 | else: 20 | return res 21 | return res 22 | # code here 23 | 24 | 25 | 26 | #{ 27 | # Driver Code Starts 28 | #Initial Template for Python 3 29 | 30 | if __name__ == "__main__": 31 | t = int(input().strip()) 32 | while t > 0: 33 | arr = list(map(int, input().strip().split())) 34 | target = int(input().strip()) 35 | ob = Solution() 36 | ans = ob.sumClosest(arr, target) 37 | if not ans: 38 | print("[]") 39 | else: 40 | print(*ans) 41 | print("~") 42 | t -= 1 43 | 44 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Easy/Pair with given sum in a sorted array/pair-with-given-sum-in-a-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | 6 | // } Driver Code Ends 7 | 8 | class Solution { 9 | public: 10 | int countPairs(vector &arr, int target) { 11 | 12 | int n=arr.size(); 13 | int count=0; 14 | unordered_mapmp; 15 | 16 | for (int i=0;i> t; 32 | cin.ignore(); 33 | while (t--) { 34 | vector arr; 35 | int target; 36 | string input; 37 | getline(cin, input); 38 | 39 | stringstream ss(input); 40 | int number; 41 | while (ss >> number) { 42 | arr.push_back(number); 43 | } 44 | cin >> target; 45 | cin.ignore(); 46 | Solution obj; 47 | cout << obj.countPairs(arr, target) << endl; 48 | cout << "~\n"; 49 | } 50 | 51 | return 0; 52 | } 53 | // } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Search in a sorted Matrix/search-in-a-sorted-matrix.py: -------------------------------------------------------------------------------- 1 | 2 | #User function Template for python3 3 | 4 | class Solution: 5 | 6 | #Function to search a given number in row-column sorted matrix. 7 | def searchMatrix(self, mat, x): 8 | n = len(mat) 9 | m = len(mat[0]) 10 | for i in range(n): 11 | for j in range(m): 12 | if mat[i][j] == x: 13 | return True 14 | return False 15 | # code here 16 | 17 | 18 | 19 | 20 | #{ 21 | # Driver Code Starts 22 | # Initial Template for Python 3 23 | 24 | if __name__ == "__main__": 25 | import sys 26 | input = sys.stdin.read 27 | data = input().split() 28 | 29 | t = int(data[0]) 30 | index = 1 31 | for _ in range(t): 32 | r = int(data[index]) 33 | c = int(data[index + 1]) 34 | index += 2 35 | matrix = [] 36 | for i in range(r): 37 | row = list(map(int, data[index:index + c])) 38 | matrix.append(row) 39 | index += c 40 | x = int(data[index]) 41 | index += 1 42 | ob = Solution() 43 | if ob.searchMatrix(matrix, x): 44 | print("true") 45 | else: 46 | print("false") 47 | print("~") 48 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Easy/Search in a row-wise sorted matrix/search-in-a-rowwise-sorted-matrix.py: -------------------------------------------------------------------------------- 1 | 2 | #User function Template for python3 3 | 4 | class Solution: 5 | 6 | #Function to search a given number in row-column sorted matrix. 7 | def searchRowMatrix(self, mat, x): 8 | n = len(mat) 9 | m = len(mat[0]) 10 | for i in range(n): 11 | for j in range(m): 12 | if mat[i][j] == x: 13 | return True 14 | return False 15 | # code here 16 | 17 | 18 | 19 | 20 | #{ 21 | # Driver Code Starts 22 | # Initial Template for Python 3 23 | 24 | if __name__ == "__main__": 25 | import sys 26 | input = sys.stdin.read 27 | data = input().split() 28 | 29 | t = int(data[0]) 30 | index = 1 31 | for _ in range(t): 32 | r = int(data[index]) 33 | c = int(data[index + 1]) 34 | index += 2 35 | matrix = [] 36 | for i in range(r): 37 | row = list(map(int, data[index:index + c])) 38 | matrix.append(row) 39 | index += c 40 | x = int(data[index]) 41 | index += 1 42 | ob = Solution() 43 | if ob.searchRowMatrix(matrix, x): 44 | print("true") 45 | else: 46 | print("false") 47 | print("~") 48 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Minimize the Heights II/minimize-the-heights-ii.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | 3 | class Solution: 4 | def getMinDiff(self, arr,k): 5 | # code here 6 | arr.sort() 7 | n = len(arr) 8 | # Step 2: Initialize the difference between the highest and lowest before any modifications 9 | result = arr[n-1] - arr[0] 10 | 11 | # Step 3: Traverse the array and adjust the heights 12 | for i in range(1, n): 13 | if arr[i] >= k: # Ensure no negative heights 14 | # Calculate the possible new minimum and maximum heights 15 | max_height = max(arr[i-1] + k, arr[n-1] - k) 16 | min_height = min(arr[0] + k, arr[i] - k) 17 | # Update the result with the minimum possible difference 18 | result = min(result, max_height - min_height) 19 | 20 | return result 21 | 22 | #{ 23 | # Driver Code Starts 24 | #Initial Template for Python 3 25 | 26 | if __name__ == '__main__': 27 | tc = int(input()) 28 | while tc > 0: 29 | k = int(input()) 30 | # n = int(input()) 31 | arr = list(map(int, input().strip().split())) 32 | ob = Solution() 33 | ans = ob.getMinDiff(arr, k) 34 | print(ans) 35 | tc -= 1 36 | 37 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Easy/Occurence of an integer in a Linked List/occurence-of-an-integer-in-a-linked-list.py: -------------------------------------------------------------------------------- 1 | """ 2 | class Node: 3 | def __init__(self, data): 4 | self.data = data 5 | self.next = None 6 | This is method only submission. 7 | You only need to complete the method. 8 | """ 9 | class Solution: 10 | def count(self, head, key): 11 | temp = head 12 | count = 0 13 | while(temp != None): 14 | if temp.data == key : 15 | count += 1 16 | temp = temp.next 17 | return count 18 | # Code here 19 | 20 | 21 | #{ 22 | # Driver Code Starts 23 | #Initial Template for Python 3 24 | 25 | 26 | class Node: 27 | 28 | def __init__(self, data): 29 | self.data = data 30 | self.next = None 31 | 32 | 33 | if __name__ == "__main__": 34 | import sys 35 | input = sys.stdin.read 36 | data = input().split('\n') 37 | 38 | t = int(data[0]) 39 | for i in range(1, t + 1): 40 | arr = list(map(int, data[2 * i - 1].split())) 41 | head = Node(arr[0]) 42 | tail = head 43 | for value in arr[1:]: 44 | tail.next = Node(value) 45 | tail = tail.next 46 | key = int(data[2 * i]) 47 | ob = Solution() 48 | print(ob.count(head, key)) 49 | print("~") 50 | 51 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Hard/Histogram Max Rectangular Area/histogram-max-rectangular-area.py: -------------------------------------------------------------------------------- 1 | #{ 2 | # Driver Code Starts 3 | #Initial Template for Python 3 4 | 5 | # } Driver Code Ends 6 | 7 | class Solution: 8 | def getMaxArea(self,arr): 9 | #code here 10 | left = [1]*len(arr) 11 | right = [1]*len(arr) 12 | 13 | for i in range(1, len(arr)): 14 | ic = i - 1 15 | while ic >= 0 and arr[i] <= arr[ic]: 16 | left[i] += left[ic] 17 | ic -= left[ic] 18 | 19 | for i in range(len(arr)-2, -1, -1): 20 | ic = i + 1 21 | while ic < len(arr) and arr[i] <= arr[ic]: 22 | right[i] += right[ic] 23 | ic += right[ic] 24 | 25 | maxi = -1 26 | 27 | for i in range(len(arr)): 28 | t = (left[i] + right[i] - 1) * arr[i] 29 | maxi = max(maxi, t) 30 | 31 | return maxi 32 | 33 | #{ 34 | # Driver Code Starts. 35 | #Initial Template for Python 3 36 | 37 | if __name__ == "__main__": 38 | t = int(input()) 39 | while t > 0: 40 | arr = list(map(int, input().split())) 41 | ob = Solution() 42 | res = ob.getMaxArea(arr) 43 | print(res) 44 | print("~") 45 | t -= 1 46 | 47 | 48 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Allocate Minimum Pages/allocate-minimum-pages.py: -------------------------------------------------------------------------------- 1 | 2 | class Solution: 3 | def findPages(self, arr, k): 4 | n = len(arr) 5 | if n < k: 6 | return -1 7 | low, high = max(arr), sum(arr) 8 | while low < high: 9 | mid = (low + high) // 2 10 | if Solution.isPossible(arr, k, mid): 11 | high = mid 12 | else: 13 | low = mid + 1 14 | 15 | return low 16 | 17 | def isPossible(arr, k, maxPages): 18 | students, currentSum = 1, 0 19 | for pages in arr: 20 | if currentSum + pages > maxPages: 21 | students += 1 22 | currentSum = pages 23 | if students > k: 24 | return False 25 | else: 26 | currentSum += pages 27 | 28 | return True 29 | 30 | #{ 31 | # Driver Code Starts 32 | #Initial Template for Python 3 33 | import bisect 34 | #Main 35 | if __name__ == '__main__': 36 | t = int(input()) 37 | while t: 38 | t -= 1 39 | A = [int(x) for x in input().strip().split()] 40 | nd = [int(x) for x in input().strip().split()] 41 | D = nd[0] 42 | ob = Solution() 43 | ans = ob.findPages(A, D) 44 | print(ans) 45 | print("~") 46 | 47 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Majority Element II/README.md: -------------------------------------------------------------------------------- 1 |

Majority Element II

Difficulty Level : Difficulty: Medium


You are given an array of integer arr[] where each number represents a vote to a candidate. Return the candidates that have votes greater than one-third of the total votes, If there's not a majority vote, return an empty array. 

2 |

Note: The answer should be returned in an increasing format.

3 |

Examples:

4 |
Input: arr[] = [2, 1, 5, 5, 5, 5, 6, 6, 6, 6, 6]
5 | Output: [5, 6]
6 | Explanation: 5 and 6 occur more n/3 times.
7 |
Input: arr[] = [1, 2, 3, 4, 5]
8 | Output: []
Explanation: no candidate occur more than n/3 times.
9 |

Constraint:
1 <= arr.size() <= 106
0 <= arr[i] <= 109

-------------------------------------------------------------------------------- /Difficulty: Easy/Power of 2/README.md: -------------------------------------------------------------------------------- 1 |

Power of 2

Difficulty Level : Difficulty: Easy


Given a non-negative integer n. The task is to check if it is a power of 2

2 |

Examples

3 |
Input: n = 8
 4 | Output: true
 5 | Explanation: 8 is equal to 2 raised to 3 (23 = 8).
6 |
Input: n = 98
 7 | Output: false
 8 | Explanation: 98 cannot be obtained by any power of 2.
9 |
Input: n = 1
10 | Output: true
11 | Explanation: (20 = 1).
12 |

Constraints:
0 ≤ n < 109

Company Tags :
Adobe 

Topic Tags :
Bit Magic Data Structures  -------------------------------------------------------------------------------- /Difficulty: Medium/Subarrays with sum K/subarrays-with-sum-k.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | from collections import defaultdict 3 | class Solution: 4 | def countSubarrays(self, arr, k): 5 | n = len(arr) 6 | curr_sum = 0 7 | max_sum = defaultdict(int) 8 | max_sum[0] = 1 9 | ans = 0 10 | for i in range(n): 11 | curr_sum += arr[i] 12 | if curr_sum - k in max_sum: 13 | ans += max_sum[curr_sum - k] 14 | max_sum[curr_sum] += 1 15 | return ans 16 | 17 | # code here 18 | 19 | 20 | 21 | #{ 22 | # Driver Code Starts 23 | #Initial Template for Python 3 24 | 25 | import atexit 26 | import io 27 | import sys 28 | from collections import deque 29 | 30 | #Contributed by : Nagendra Jha 31 | 32 | _INPUT_LINES = sys.stdin.read().splitlines() 33 | input = iter(_INPUT_LINES).__next__ 34 | _OUTPUT_BUFFER = io.StringIO() 35 | sys.stdout = _OUTPUT_BUFFER 36 | 37 | 38 | @atexit.register 39 | def write(): 40 | sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) 41 | 42 | 43 | if __name__ == '__main__': 44 | test_cases = int(input()) 45 | for cases in range(test_cases): 46 | k = int(input()) 47 | arr = list(map(int, input().strip().split())) 48 | ob = Solution() 49 | res = ob.countSubarrays(arr, k) 50 | print(res) 51 | print("~") 52 | 53 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Easy/Max distance between same elements/max-distance-between-same-elements.java: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | import java.util.*; 3 | import java.util.Scanner; 4 | 5 | 6 | // } Driver Code Ends 7 | class Solution { 8 | public int maxDistance(int[] arr) { 9 | // Code here 10 | int maxDist = 0; 11 | HashMap map = new HashMap<>(); 12 | for(int i=0;i 0) { 31 | String input = sc.nextLine(); 32 | String[] parts = input.split(" "); 33 | int[] arr = new int[parts.length]; 34 | for (int i = 0; i < parts.length; i++) { 35 | arr[i] = Integer.parseInt(parts[i]); 36 | } 37 | Solution ob = new Solution(); 38 | System.out.println(ob.maxDistance(arr)); 39 | } 40 | sc.close(); 41 | } 42 | } 43 | // } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Basic/Binary representation/README.md: -------------------------------------------------------------------------------- 1 |

Binary representation

Difficulty Level : Difficulty: Basic


You are given an integer n, you need to return its binary representation in the form of a string.
Note: String must contain 32 bits.

2 |

Examples:

3 |
Input: n = 2
4 | Output: 00000000000000000000000000000010
5 | Explanation: The binary representation of 2 is '10', so it can be represent as 00000000000000000000000000000010 in 32 bits.
6 |
Input: n = 5
7 | Output: 00000000000000000000000000000101
8 | Explanation: The binary representation of 5 is '101', so it can be represent as 00000000000000000000000000000101 in 32 bits.
9 |

Constraints:
1 ≤ n ≤ 109

Company Tags :
Microsoft 

Topic Tags :
Bit Magic Data Structures  -------------------------------------------------------------------------------- /Difficulty: Easy/Sieve of Eratosthenes/sieve-of-eratosthenes.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | 6 | // } Driver Code Ends 7 | 8 | // User function Template for C++ 9 | class Solution { 10 | public: 11 | vector sieveOfEratosthenes(int n) { 12 | vector isPrime(n + 1, true); 13 | vector primes; 14 | 15 | if (n < 2) 16 | return primes; 17 | 18 | isPrime[0] = false; 19 | isPrime[1] = false; 20 | 21 | for (int i = 2; i * i <= n; i++) { 22 | if (isPrime[i]) { 23 | for (int j = i * i; j <= n; j += i) { 24 | isPrime[j] = false; 25 | } 26 | } 27 | } 28 | 29 | for (int i = 2; i <= n; i++) { 30 | if (isPrime[i]) { 31 | primes.push_back(i); 32 | } 33 | } 34 | 35 | return primes; 36 | } 37 | }; 38 | 39 | 40 | //{ Driver Code Starts. 41 | int main() { 42 | int t; 43 | cin >> t; 44 | while (t--) { 45 | int n; 46 | cin >> n; 47 | Solution ob; 48 | vector primes = ob.sieveOfEratosthenes(n); 49 | for (auto prime : primes) { 50 | cout << prime << " "; 51 | } 52 | cout << endl; 53 | 54 | cout << "~" 55 | << "\n"; 56 | } 57 | return 0; 58 | } 59 | // } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Hard/Min Chars to Add for Palindrome/README.md: -------------------------------------------------------------------------------- 1 |

Min Chars to Add for Palindrome

Difficulty Level : Difficulty: Hard


Given a string s, the task is to find the minimum characters to be added at the front to make the string palindrome.

2 |

Note: A palindrome string is a sequence of characters that reads the same forward and backward.

3 |

Examples:

4 |
Input: s = "abc"
 5 | Output: 2
 6 | Explanation: Add 'b' and 'c' at front of above string to make it palindrome : "cbabc"
 7 | 
8 |
Input: s = "aacecaaaa"
 9 | Output: 2
10 | Explanation: Add 2 a's at front of above string to make it palindrome : "aaaacecaaaa"
11 |

Constraints:
1 <= s.size() <= 106


Topic Tags :
Strings Data Structures  -------------------------------------------------------------------------------- /Difficulty: Medium/Smallest Positive Missing Number/smallest-positive-missing-number.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | 6 | // } Driver Code Ends 7 | 8 | class Solution { 9 | public: 10 | // Function to find the smallest positive number missing from the array. 11 | int missingNumber(vector &arr) { 12 | // Your code here 13 | int n = arr.size(); 14 | for(int i = 0;i < n;i++){ 15 | while(arr[i] != i+1 && arr[i] > 0 && arr[i] <= n){ 16 | if(arr[i] == arr[arr[i]-1]) break; 17 | swap(arr[i],arr[arr[i]-1]); 18 | 19 | } 20 | } 21 | for(int i = 0;i < n;i++) if(arr[i] != i+1) return i+1; 22 | return n+1; 23 | } 24 | }; 25 | 26 | 27 | //{ Driver Code Starts. 28 | 29 | // int missingNumber(int arr[], int n); 30 | 31 | int main() { 32 | 33 | // taking testcases 34 | int t; 35 | cin >> t; 36 | cin.ignore(); 37 | while (t--) { 38 | 39 | vector arr; 40 | string input; 41 | getline(cin, input); 42 | stringstream ss(input); 43 | int number; 44 | while (ss >> number) { 45 | arr.push_back(number); 46 | } 47 | 48 | Solution ob; 49 | int result = ob.missingNumber(arr); 50 | cout << result << "\n"; 51 | } 52 | return 0; 53 | } 54 | // } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Implement Pow/README.md: -------------------------------------------------------------------------------- 1 |

Implement Pow

Difficulty Level : Difficulty: Medium


Implement the function power(b, e), which calculates b raised to the power of e (i.e. be).

2 |

Examples:

3 |
Input: b = 3.00000, e = 5
Output: 243.00000
4 |
Input: b = 0.55000, e = 3
Output: 0.16638
5 |
Input: b = -0.67000, e = -7
Output: -16.49971
6 |

Constraints:

7 |
    8 |
  • -100.0 < b < 100.0
  • 9 |
  • -109 <= e <= 109
  • 10 |
  • Either b is not zero or e > 0.
  • 11 |
  • -104 <= be <= 104
  • 12 |
-------------------------------------------------------------------------------- /Difficulty: Easy/Count pairs with given sum/count-pairs-with-given-sum.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | 6 | // } Driver Code Ends 7 | class Solution { 8 | public: 9 | int countPairs(vector &arr, int target) { 10 | // Code here 11 | unordered_map freq; 12 | int count = 0; 13 | 14 | for (int num : arr) { 15 | // Check if the complement (target - num) exists in the map 16 | int complement = target - num; 17 | if (freq.find(complement) != freq.end()) { 18 | count += freq[complement]; 19 | } 20 | 21 | // Update the frequency of the current number 22 | freq[num]++; 23 | } 24 | 25 | return count; 26 | } 27 | }; 28 | 29 | //{ Driver Code Starts. 30 | 31 | int main() { 32 | int t; 33 | cin >> t; 34 | cin.ignore(); 35 | while (t--) { 36 | vector arr; 37 | string input; 38 | getline(cin, input); 39 | stringstream ss(input); 40 | int number; 41 | while (ss >> number) { 42 | arr.push_back(number); 43 | } 44 | int target; 45 | cin >> target; 46 | cin.ignore(); 47 | Solution ob; 48 | int res = ob.countPairs(arr, target); 49 | 50 | cout << res << endl << "~" << endl; 51 | } 52 | return 0; 53 | } 54 | // } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Hard/Max Circular Subarray Sum/max-circular-subarray-sum.java: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | import java.io.*; 3 | import java.util.*; 4 | 5 | class Sorting { 6 | public static void main(String[] args) throws Exception { 7 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 8 | int t = Integer.parseInt(br.readLine()); 9 | for (int g = 0; g < t; g++) { 10 | String[] str = (br.readLine()).trim().split(" "); 11 | int arr[] = new int[str.length]; 12 | for (int i = 0; i < str.length; i++) arr[i] = Integer.parseInt(str[i]); 13 | System.out.println(new Solution().circularSubarraySum(arr)); 14 | // System.out.println("~"); 15 | } 16 | } 17 | } 18 | // } Driver Code Ends 19 | 20 | class Solution { 21 | public int circularSubarraySum(int arr[]) { 22 | int prefixSum = 0; 23 | int maxSum = Integer.MIN_VALUE; 24 | 25 | int sum = 0; 26 | for (int num : arr) { 27 | sum += num; 28 | prefixSum += num; 29 | maxSum = Math.max(maxSum, sum); 30 | sum = Math.max(sum, 0); 31 | } 32 | 33 | int currSum = 0; 34 | for (int num : arr) { 35 | currSum += num; 36 | currSum = Math.min(0, currSum); 37 | maxSum = Math.max(maxSum, prefixSum - currSum); 38 | } 39 | 40 | return maxSum; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Difficulty: Easy/Single Number/README.md: -------------------------------------------------------------------------------- 1 |

Single Number

Difficulty Level : Difficulty: Easy


Given an array arr[] of positive integers where every element appears even times except for one. Find that number occurring an odd number of times.

2 |

Examples:

3 |
Input: arr[] = [1, 1, 2, 2, 2]
 4 | Output: 2
 5 | Explanation: In the given array all element appear two times except 2 which appears thrice.
6 |
Input: arr[] = [8, 8, 7, 7, 6, 6, 1]
 7 | Output: 1
 8 | Explanation: In the given array all element appear two times except 1 which appears once.
9 |

Expected Time Complexity: O(n)
Expected Auxiliary Space: O(1)

10 |

Constraints:
1 ≤ arr.size() ≤ 106
0 ≤ arri ≤ 105

Company Tags :
Amazon 

Topic Tags :
Arrays Data Structures  -------------------------------------------------------------------------------- /Difficulty: Medium/Find triplets with zero sum/find-triplets-with-zero-sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | #Function to find triplets with zero sum. 3 | def findTriplets(self, arr, n): 4 | count = 0 5 | arr.sort() 6 | 7 | for i in range(n-2): 8 | if (i > 0 and arr[i] == arr[i-1]): 9 | continue 10 | 11 | j, k = i+1, n-1 12 | while (j < k): 13 | sum_of_3 = arr[i] + arr[j] + arr[k] 14 | if sum_of_3 == 0: 15 | count += 1 16 | j += 1 17 | k -= 1 18 | elif sum_of_3 < 0: 19 | j += 1 20 | else: 21 | k -= 1 22 | 23 | return count 24 | 25 | #{ 26 | # Driver Code Starts 27 | #Initial Template for Python 3 28 | 29 | import atexit 30 | import io 31 | import sys 32 | 33 | _INPUT_LINES = sys.stdin.read().splitlines() 34 | input = iter(_INPUT_LINES).__next__ 35 | _OUTPUT_BUFFER = io.StringIO() 36 | sys.stdout = _OUTPUT_BUFFER 37 | 38 | 39 | @atexit.register 40 | def write(): 41 | sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) 42 | 43 | 44 | if __name__ == '__main__': 45 | t = int(input()) 46 | for i in range(t): 47 | n = int(input()) 48 | a = list(map(int, input().strip().split())) 49 | if (Solution().findTriplets(a, n)): 50 | print(1) 51 | else: 52 | print(0) 53 | 54 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Minimize the Heights I/minimize-the-heights-i.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | // Initial template for C++ 3 | #include 4 | using namespace std; 5 | 6 | 7 | // } Driver Code Ends 8 | // User function Template for C++ 9 | 10 | class Solution { 11 | public: 12 | int getMinDiff(int k, vector &arr) { 13 | int n=arr.size(); 14 | sort(arr.begin(),arr.end()); 15 | int mini=arr[0]; 16 | int maxi=arr[n-1]; 17 | 18 | int ans=maxi-mini; 19 | 20 | for(int i=1;i> t; 36 | cin.ignore(); 37 | 38 | while (t--) { 39 | int k; 40 | cin >> k; 41 | cin.ignore(); 42 | vector arr; 43 | string input; 44 | getline(cin, input); 45 | stringstream ss(input); 46 | int number; 47 | while (ss >> number) { 48 | arr.push_back(number); 49 | } 50 | int n = arr.size(); 51 | Solution ob; 52 | int res = ob.getMinDiff(k, arr); 53 | cout << res; 54 | 55 | cout << "\n"; 56 | cout << "~" 57 | << "\n"; 58 | } 59 | return 0; 60 | } 61 | // } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Easy/Number of 1 Bits/README.md: -------------------------------------------------------------------------------- 1 |

Number of 1 Bits

Difficulty Level : Difficulty: Easy


Given a positive integer n. Your task is to return the count of set bits.

2 |

Examples:

3 |
Input: n = 6
 4 | Output: 2
 5 | Explanation: Binary representation is '110', so the count of the set bit is 2.
6 |
Input: n = 8
 7 | Output: 1
 8 | Explanation: Binary representation is '1000', so the count of the set bit is 1.
9 |
Input: n = 3
10 | Output: 2
11 |

Constraints:
1 ≤ n ≤ 109

Company Tags :
Microsoft Samsung Adobe Wipro Brocade Juniper Networks Cisco Qualcomm 

Topic Tags :
Bit Magic Data Structures  -------------------------------------------------------------------------------- /Difficulty: Easy/Count the Zeros/README.md: -------------------------------------------------------------------------------- 1 |

Count the Zeros

Difficulty Level : Difficulty: Easy


Given an array arr of only 0's and 1's. The array is sorted in such a manner that all the 1's are placed first and then they are followed by all the 0's. Find the count of all the 0's.

2 |

Examples:

3 |
Input: arr[] = [1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0]
4 | Output: 3
5 | Explanation: There are 3 0's in the given array.
6 |
Input: arr[] = [0, 0, 0, 0, 0]
7 | Output: 5
8 | Explanation: There are 5 0's in the array.
9 |

Constraints:
1 <= arr.size <= 105
0 <= arr[i] <= 1

Company Tags :
Amazon Yahoo 

Topic Tags :
Arrays Searching Data Structures Algorithms  -------------------------------------------------------------------------------- /Difficulty: Easy/Pairs with difference k/README.md: -------------------------------------------------------------------------------- 1 |

Pairs with difference k

Difficulty Level : Difficulty: Easy


Given an array arr[] of positive integers. Find the number of pairs of integers whose difference equals a given number k.
Note: (a, b) and (b, a) are considered the same. Also, the same numbers at different indices are considered different.

2 |

Examples:

3 |
Input: arr[] = [1, 5, 3, 4, 2], k = 3
4 | Output: 2
5 | Explanation: There are 2 pairs with difference 3,the pairs are {1, 4} and {5, 2} 
6 |
Input: arr[] = [8, 12, 16, 4, 0, 20], k = 4
7 | Output: 5
8 | Explanation: There are 5 pairs with difference 4, the pairs are {0, 4}, {4, 8}, {8, 12}, {12, 16} and {16, 20}.
9 |

Constraints:
1 <= arr.size() <= 106
1 <= k <= 106
1 <= arri <= 106

Company Tags :
Adobe 

Topic Tags :
Arrays Data Structures  -------------------------------------------------------------------------------- /Difficulty: Medium/Add Binary Strings/README.md: -------------------------------------------------------------------------------- 1 |

Add Binary Strings

Difficulty Level : Difficulty: Medium


Given two binary strings s1 and s2 consisting of only 0s and 1s. Find the resultant string after adding the two Binary Strings.
Note: The input strings may contain leading zeros but the output string should not have any leading zeros.

2 |
Input: s1 = "1101", s2 = "111"
 3 | Output: 10100
 4 | Explanation:
 5 |  1101
 6 | + 111
 7 | 10100
 8 | 
9 |
Input: s1 = "00100", s2 = "010"
10 | Output: 110
11 | Explanation: 
12 |   100
13 | +  10
14 |   110
15 | 
16 |

Constraints:
1 ≤s1.size(), s2.size()≤ 106

Company Tags :
Amazon Microsoft Facebook 

Topic Tags :
Strings Mathematical Data Structures Algorithms  -------------------------------------------------------------------------------- /Difficulty: Medium/Minimum sum/minimum-sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minSum(self, arr): 3 | n = len(arr) 4 | if 0 == n: 5 | return 0 6 | if 1 == n: 7 | return arr[0] 8 | freq = [0] * 10 9 | for digit in arr: 10 | if digit: 11 | freq[digit] += 1 12 | s = [] 13 | remainder = 0 14 | odd = False 15 | for digit in range(9, 0, -1): 16 | count = freq[digit] 17 | if count: 18 | if odd: 19 | remainder += digit 20 | count -= 1 21 | s.append(str(remainder % 10)) 22 | remainder //= 10 23 | odd = False 24 | for _ in range(count // 2): 25 | remainder += digit * 2 26 | s.append(str(remainder % 10)) 27 | remainder //= 10 28 | if count % 2: 29 | odd = True 30 | remainder += digit 31 | if remainder: 32 | s.append(str(remainder)) 33 | s.reverse() 34 | return ''.join(s) 35 | 36 | 37 | #{ 38 | # Driver Code Starts 39 | #Initial Template for Python 3 40 | 41 | if __name__ == '__main__': 42 | tc = int(input()) 43 | while tc > 0: 44 | arr = list(map(int, input().strip().split())) 45 | ob = Solution() 46 | ans = ob.minSum(arr) 47 | print(ans) 48 | tc -= 1 49 | 50 | print("~") 51 | 52 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Subarray range with given sum/README.md: -------------------------------------------------------------------------------- 1 |

Subarray range with given sum

Difficulty Level : Difficulty: Medium


Given an unsorted array of integers arr[], and a target tar, determine the number of subarrays whose elements sum up to the target value.

2 |

Examples:

3 |
Input: arr[] = [10, 2, -2, -20, 10] , tar = -10
 4 | Output: 3
 5 | Explanation: Subarrays with sum -10 are: [10, 2, -2, -20], [2, -2, -20, 10] and [-20, 10].
 6 | 
7 |
Input: arr[] = [1, 4, 20, 3, 10, 5] , tar = 33
 8 | Output: 1
 9 | Explanation: Subarray with sum 33 is: [20,3,10].
10 |

Expected Time Complexity: O(n)
Expected Auxilary Space: O(n)

11 |

Constraints:
1 <= arr.size() <= 106
-105 <= arr[i] <= 105
-105 <= tar <= 105


Topic Tags :
Arrays Hash Data Structures  -------------------------------------------------------------------------------- /Difficulty: Basic/Largest Element in Array/README.md: -------------------------------------------------------------------------------- 1 |

Largest Element in Array

Difficulty Level : Difficulty: Basic


Given an array arr[]. The task is to find the largest element and return it.

2 |

Examples:

3 |
Input: arr[] = [1, 8, 7, 56, 90]
 4 | Output: 90
 5 | Explanation: The largest element of the given array is 90.
6 |
Input: arr[] = [5, 5, 5, 5]
 7 | Output: 5
 8 | Explanation: The largest element of the given array is 5.
9 |
Input: arr[] = [10]
10 | Output: 10
11 | Explanation: There is only one element which is the largest.
12 |

Constraints:
1 <= arr.size()<= 106
0 <= arr[i] <= 106

Company Tags :
Infosys Oracle Wipro Morgan Stanley 

Topic Tags :
Arrays Data Structures  -------------------------------------------------------------------------------- /Difficulty: Easy/Find the Sum of Last N nodes of the Linked List/find-the-sum-of-last-n-nodes-of-the-linked-list.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | 3 | ''' 4 | # Node Class 5 | class Node: 6 | def __init__(self, data): # data -> value stored in node 7 | self.data = data 8 | self.next = None 9 | ''' 10 | class Solution: 11 | def sumOfLastN_Nodes(self, head, n): 12 | count=0 13 | temp=head 14 | while (temp is not None): 15 | count+=1 16 | temp=temp.next 17 | 18 | k=count-n 19 | temp=head 20 | ans=0 21 | while(k>0): 22 | temp=temp.next 23 | k-=1 24 | while(temp is not None): 25 | ans+=temp.data 26 | temp=temp.next 27 | return ans 28 | 29 | 30 | #{ 31 | # Driver Code Starts 32 | #Initial Template for Python 3 33 | 34 | 35 | class Node: 36 | 37 | def __init__(self, data): 38 | self.data = data 39 | self.next = None 40 | 41 | 42 | if __name__ == "__main__": 43 | import sys 44 | input = sys.stdin.read 45 | data = input().split('\n') 46 | 47 | t = int(data[0]) 48 | for i in range(1, t + 1): 49 | arr = list(map(int, data[2 * i - 1].split())) 50 | n = int(data[2 * i]) 51 | head = Node(arr[0]) 52 | tail = head 53 | for value in arr[1:]: 54 | tail.next = Node(value) 55 | tail = tail.next 56 | ob = Solution() 57 | print(ob.sumOfLastN_Nodes(head, n)) 58 | 59 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Insert Interval/insert-interval.py: -------------------------------------------------------------------------------- 1 | #{ 2 | # Driver Code Starts 3 | #Initial Template for Python 3 4 | 5 | # } Driver Code Ends 6 | #User function Template for python3 7 | 8 | class Solution: 9 | def insertInterval(self, intervals, newInterval): 10 | # Code here 11 | def merge(i1, i2): 12 | if i2[0] < i1[0]: 13 | i1, i2 = i2, i1 14 | if i1[1] < i2[0]: 15 | return i1, i2 16 | return None, (min(i1[0], i2[0]), max(i1[1], i2[1])) 17 | 18 | res = [] 19 | for i in intervals: 20 | into, newInterval = merge(i, newInterval) 21 | if into: 22 | res.append(into) 23 | 24 | res.append(newInterval) 25 | return res 26 | 27 | # Code here 28 | 29 | #{ 30 | # Driver Code Starts. 31 | if __name__ == '__main__': 32 | t = int(input ()) 33 | for _ in range (t): 34 | N = int(input()) 35 | intervals = [list(map(int, input().split())) for i in range(N)] 36 | newEvent = list(map(int, input().split())) 37 | ob = Solution() 38 | res = ob.insertInterval(intervals, newEvent) 39 | print('[', end = '') 40 | for i in range(len(res)): 41 | print('[', end = '') 42 | print(str(res[i][0])+','+str(res[i][1]), end = '') 43 | print(']', end = '') 44 | if i < len(res)-1: 45 | print(',', end='') 46 | print(']') 47 | print("~") 48 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Easy/Split Linked List Alternatingly/split-linked-list-alternatingly.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | ''' 3 | class Node: 4 | def _init_(self, data): 5 | self.data = data 6 | self.next = None 7 | 8 | ''' 9 | class Solution: 10 | def alternatingSplitList(self, head): 11 | dummy=[Node(None),Node(None)] 12 | odd=0 13 | cur=head 14 | dum=[dummy[0],dummy[1]] 15 | while cur: 16 | dum[odd].next=cur 17 | dum[odd]=dum[odd].next 18 | odd=(odd+1)%2 19 | cur=cur.next 20 | dum[0].next=None 21 | dum[1].next=None 22 | dummy[0]=dummy[0].next 23 | dummy[1]=dummy[1].next 24 | return dummy 25 | 26 | 27 | 28 | #{ 29 | # Driver Code Starts 30 | class Node: 31 | 32 | def __init__(self, x): 33 | self.data = x 34 | self.next = None 35 | 36 | 37 | def printList(node): 38 | while node is not None: 39 | print(node.data, end=" ") 40 | node = node.next 41 | print() 42 | 43 | 44 | if __name__ == "__main__": 45 | t = int(input().strip()) 46 | 47 | for _ in range(t): 48 | arr = list(map(int, input().strip().split())) 49 | 50 | head = Node(arr[0]) 51 | tail = head 52 | 53 | for i in range(1, len(arr)): 54 | tail.next = Node(arr[i]) 55 | tail = tail.next 56 | 57 | ob = Solution() 58 | result = ob.alternatingSplitList(head) 59 | printList(result[0]) 60 | printList(result[1]) 61 | 62 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Not a subset sum/README.md: -------------------------------------------------------------------------------- 1 |

Not a subset sum

Difficulty Level : Difficulty: Medium


Given a sorted array arr[] of positive integers, find the smallest positive integer such that it cannot be represented as the sum of elements of any subset of the given array set.

2 |

Examples:

3 |
Input: arr[] = [1, 2, 3]
 4 | Output: 7
 5 | Explanation: 7 is the smallest positive number for which no subset is there with sum 7.
 6 | 
7 |
Input: arr[] = [3, 6, 9, 10, 20, 28]
 8 | Output: 1
 9 | Explanation: 1 is the smallest positive number for which no subset is there with sum 1.
10 | 
11 |

Expected Time Complexity: O(n)
Expected Auxiliary Space: O(1)

12 |

Constraints
1 <= arr.size() <= 106
1 <= arr[i] <= 108

 

Company Tags :
Salesforce 

Topic Tags :
Arrays Data Structures  -------------------------------------------------------------------------------- /Difficulty: Medium/Implement Atoi/implement-atoi.java: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | // Initial template for JAVA 3 | 4 | import java.util.Scanner; 5 | 6 | class Main { 7 | public static void main(String args[]) { 8 | Scanner sc = new Scanner(System.in); 9 | int t = sc.nextInt(); 10 | sc.nextLine(); 11 | while (t > 0) { 12 | String str = sc.nextLine(); 13 | 14 | Solution obj = new Solution(); 15 | int num = obj.myAtoi(str); 16 | System.out.println(num); 17 | System.out.println("~"); 18 | t--; 19 | } 20 | } 21 | } 22 | // } Driver Code Ends 23 | 24 | class Solution { 25 | public int myAtoi(String s) { 26 | // Your code here 27 | int i = 0; 28 | while (i < s.length() && s.charAt(i) == ' ') { 29 | i++; 30 | } 31 | 32 | int sign = 1; 33 | if (i < s.length() && (s.charAt(i) == '+' || s.charAt(i) == '-')) { 34 | if (s.charAt(i) == '-') { 35 | sign = -1; 36 | } 37 | i++; 38 | } 39 | 40 | long result = 0; 41 | while (i < s.length() && Character.isDigit(s.charAt(i))) { 42 | result = result * 10 + (s.charAt(i) - '0'); 43 | 44 | if (result * sign > Integer.MAX_VALUE) { 45 | return Integer.MAX_VALUE; 46 | } 47 | if (result * sign < Integer.MIN_VALUE) { 48 | return Integer.MIN_VALUE; 49 | } 50 | i++; 51 | } 52 | 53 | return (int) (result * sign); 54 | } 55 | } -------------------------------------------------------------------------------- /Difficulty: Easy/Remove duplicates in array/README.md: -------------------------------------------------------------------------------- 1 |

Remove duplicates in array

Difficulty Level : Difficulty: Easy


Given an array arr consisting of positive integers numbers, remove all duplicates numbers.

2 |

Example:

3 |
Input: arr[] = [2, 2, 3, 3, 7, 5] 
Output: [2, 3, 7, 5]
Explanation: After removing the duplicates 2 and 3 we get 2 3 7 5.
4 |
Input: arr[] = [2, 2, 5, 5, 7, 7] 
Output: [2, 5, 7]
Explanation: After removing the duplicates 2, 5 and 7 we get 2 5 7.
5 |

Expected Time Complexity: O(n)
Expected Auxiliary Space: O(1)

6 |

Constraints:
1<= arr.size() <=106
2<=arr[i]<=100

Company Tags :
Amazon 

Topic Tags :
Arrays Hash Prime Number Data Structures  -------------------------------------------------------------------------------- /Difficulty: Easy/Sorted and Rotated Minimum/README.md: -------------------------------------------------------------------------------- 1 |

Sorted and Rotated Minimum

Difficulty Level : Difficulty: Easy


A sorted array arr[] (may contain duplicates) is rotated at some unknown point, the task is to find the minimum element in it. 

2 |

Examples:

3 |
Input: arr[] = [5, 6, 1, 2, 3, 4]
 4 | Output: 1
 5 | Explanation: 1 is the minimum element in the array.
6 |
Input: arr[] = [3, 2, 2, 2]
 7 | Output: 2
 8 | Explanation: Here 2 is the minimum element.
9 |
Input: arr[] = [4, 4, 4]
10 | Output: 4
11 | Explanation: Here 4 is the only minimum element.
12 |

Constraints:
1 ≤ arr.size() ≤ 106
1 ≤ arr[i] ≤ 109

Company Tags :
Morgan Stanley Amazon Microsoft Samsung Snapdeal Adobe Times Internet 

Topic Tags :
Searching Algorithms  -------------------------------------------------------------------------------- /Difficulty: Easy/Longest substring with distinct characters/README.md: -------------------------------------------------------------------------------- 1 |

Longest substring with distinct characters

Difficulty Level : Difficulty: Easy


Given a string s, find the length of the longest substring with all distinct characters. 

2 |

Examples:

3 |
Input: s = "geeksforgeeks"
 4 | Output: 7
 5 | Explanation: "eksforg" is the longest substring with all distinct characters.
 6 | 
7 |
Input: s = "aaa"
 8 | Output: 1
 9 | Explanation: "a" is the longest substring with all distinct characters.
10 |
Input: s = "abcdefabcbb"
11 | Output: 6
12 | Explanation: The longest substring with all distinct characters is "abcdef", which has a length of 6.
13 |

Constraints:
1<= s.size()<=3*104
All the characters are in lowercase.

Company Tags :
Amazon Microsoft Housing.com Adobe 

Topic Tags :
Strings Data Structures  -------------------------------------------------------------------------------- /Difficulty: Medium/Minimum sum/README.md: -------------------------------------------------------------------------------- 1 |

Minimum sum

Difficulty Level : Difficulty: Medium


Given an array arr[] such that each element is in the range [0 - 9], find the minimum possible sum of two numbers formed using the elements of the array. All digits in the given array must be used to form the two numbers. Return a string without leading zeroes.
Examples :

2 |
Input: arr[] = [6, 8, 4, 5, 2, 3]
 3 | Output: 604
 4 | Explanation: The minimum sum is formed by numbers 358 and 246.
5 |
Input: arr[] = [5, 3, 0, 7, 4]
 6 | Output: 82
 7 | Explanation: The minimum sum is formed by numbers 35 and 047.
8 |
Input: arr[] = [9, 4]
 9 | Output: 13
10 | Explanation: The minimum sum is formed by numbers 9 and 4.
11 |

Constraints:
1 ≤ arr.size() ≤ 106
0 ≤ arr[i] ≤ 9

Company Tags :
Google 

Topic Tags :
Arrays Sorting Binary Search Data Structures Algorithms  -------------------------------------------------------------------------------- /Difficulty: Easy/Reverse a linked list/reverse-a-linked-list.py: -------------------------------------------------------------------------------- 1 | #function Template for python3 2 | 3 | """ 4 | # Node Class 5 | 6 | class Node: 7 | def __init__(self, val): 8 | self.data = val 9 | self.next = None 10 | 11 | """ 12 | 13 | class Solution: 14 | def reverseList(self, head): 15 | # Code here 16 | dummy = Node(0) 17 | while head: 18 | h = head.next 19 | head.next = dummy.next 20 | dummy.next = head 21 | head = h 22 | return dummy.next 23 | 24 | 25 | 26 | 27 | #{ 28 | # Driver Code Starts 29 | # Node Class 30 | class Node: 31 | 32 | def __init__(self, val): 33 | self.data = val 34 | self.next = None 35 | 36 | 37 | # Linked List Class 38 | class Linked_List: 39 | 40 | def __init__(self): 41 | self.head = None 42 | self.tail = None 43 | 44 | def insert(self, val): 45 | if self.head is None: 46 | self.head = Node(val) 47 | self.tail = self.head 48 | else: 49 | self.tail.next = Node(val) 50 | self.tail = self.tail.next 51 | 52 | 53 | def printList(head): 54 | tmp = head 55 | while tmp: 56 | print(tmp.data, end=' ') 57 | tmp = tmp.next 58 | print() 59 | 60 | 61 | if __name__ == '__main__': 62 | for i in range(int(input())): 63 | 64 | arr = [int(x) for x in input().split()] 65 | 66 | lis = Linked_List() 67 | for i in arr: 68 | lis.insert(i) 69 | 70 | newHead = Solution().reverseList(lis.head) 71 | printList(newHead) 72 | print("~") 73 | 74 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Easy/Second Largest/README.md: -------------------------------------------------------------------------------- 1 |

Second Largest

Difficulty Level : Difficulty: Easy


Given an array arr, return the second largest distinct element from an array. If the second largest element doesn't exist then return -1.

2 |

Examples:

3 |
Input: arr = [12, 35, 1, 10, 34, 1]
 4 | Output: 34
 5 | Explanation: The largest element of the array is 35 and the second largest element is 34.
6 |
Input: arr = [10, 10]
 7 | Output: -1
 8 | Explanation: The largest element of the array is 10 and the second largest element does not exist..
9 |

Expected Time Complexity: O(n)
Expected Auxiliary Space: O(1)

10 |

Constraints:
2 ≤ arr.size() ≤ 105
1 ≤ arr[i] ≤ 105

Company Tags :
SAP Labs Rockstand 

Topic Tags :
Arrays Searching Data Structures Algorithms  -------------------------------------------------------------------------------- /Difficulty: Easy/Find All Triplets with Zero Sum/find-all-triplets-with-zero-sum.py: -------------------------------------------------------------------------------- 1 | #{ 2 | # Driver Code Starts 3 | #Initial Template for Python 3 4 | 5 | import math 6 | 7 | 8 | # } Driver Code Ends 9 | #User function Template for python3 10 | 11 | class Solution: 12 | def findTriplets(self, arr): 13 | # Your code here 14 | d={} 15 | n=len(arr) 16 | temp=0 17 | for i in range(0,n): 18 | for j in range(i+1,n): 19 | temp=arr[i]+arr[j] 20 | if(temp in d): 21 | d[temp].append([i,j]) 22 | else: 23 | d[temp]=[[i,j]] 24 | tpt=[] 25 | vis={} 26 | ans=[] 27 | for i in range(n): 28 | temp=-arr[i] 29 | if(temp in d): 30 | for a,b in d[temp]: 31 | tpt=sorted([i,a,b]) 32 | if(i!=a and i!=b and (tuple(tpt) not in vis)): 33 | ans.append(tpt) 34 | vis[tuple(tpt)]=1 35 | return ans 36 | 37 | #{ 38 | # Driver Code Starts. 39 | 40 | def main(): 41 | T = int(input()) 42 | while (T > 0): 43 | 44 | A = [int(x) for x in input().strip().split()] 45 | 46 | ob = Solution() 47 | res = ob.findTriplets(A) 48 | res = sorted(res) 49 | if len(res) == 0: 50 | print('[]') 51 | for i in range(len(res)): 52 | for j in range(len(res[i])): 53 | print(res[i][j], end=" ") 54 | print("") 55 | print('~') 56 | T -= 1 57 | 58 | 59 | if __name__ == "__main__": 60 | main() 61 | 62 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Nearly sorted/README.md: -------------------------------------------------------------------------------- 1 |

Nearly sorted

Difficulty Level : Difficulty: Medium


Given an array arr[], where each element is at most k away from its target position, you need to sort the array optimally.

2 |

Note: DO NOT use STL sort() function for this question.

3 |

Examples:

4 |
Input: arr[] = [6, 5, 3, 2, 8, 10, 9], k = 3
 5 | Output: [2, 3, 5, 6, 8, 9, 10]
 6 | Explanation: The sorted array will be 2 3 5 6 8 9 10
 7 | 
8 |
Input: arr[]= [1, 4, 5, 2, 3, 6, 7, 8, 9, 10], k = 2
 9 | Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Explanation: The sorted array will be 1 2 3 4 5 6 7 8 9 10
10 |

Constraints:
1 ≤ arr.size() ≤ 106
1 ≤ k < arr.size()
1 ≤ arri ≤ 106

Company Tags :
Google 

Topic Tags :
Sorting Arrays priority-queue  -------------------------------------------------------------------------------- /Difficulty: Easy/Largest subarray of 0's and 1's/README.md: -------------------------------------------------------------------------------- 1 |

Largest subarray of 0's and 1's

Difficulty Level : Difficulty: Easy


Given an array arr of 0s and 1s. Find and return the length of the longest subarray with equal number of 0s and 1s.

2 |

Examples:

3 |
Input: arr[] = [1, 0, 1, 1, 1, 0, 0]
 4 | Output: 6
 5 | Explanation: arr[1...6] is the longest subarray with three 0s and three 1s.
6 |
Input: arr[] = [0, 0, 1, 1, 0]
 7 | Output: 4
Explnation: arr[0...3] or arr[1...4] is the longest subarray with two 0s and two 1s.
8 |
Input: arr[] = [0]
 9 | Output: 0
Explnation: There is no subarray with an equal number of 0s and 1s.
10 |

Constraints:
1 <= arr.size() <= 105
0 <= arr[i] <= 1

Company Tags :
Paytm Morgan Stanley Amazon MakeMyTrip 

Topic Tags :
sliding-window Hash Data Structures Algorithms  -------------------------------------------------------------------------------- /Difficulty: Hard/Longest Prefix Suffix/README.md: -------------------------------------------------------------------------------- 1 |

Longest Prefix Suffix

Difficulty Level : Difficulty: Hard


Given a string of characters, find the length of the longest proper prefix which is also a proper suffix.

2 |

NOTE: Prefix and suffix can be overlapping but they should not be equal to the entire string.

3 |

Examples :

4 |
Input: str = "abab"
 5 | Output: 2
 6 | Explanation: "ab" is the longest proper prefix and suffix. 
7 |
Input: str = "aaaa"
 8 | Output: 3
 9 | Explanation: "aaa" is the longest proper prefix and suffix. 
10 |

Expected Time Complexity: O(|str|)
Expected Auxiliary Space: O(|str|)

11 |

Constraints:
1 ≤ |str| ≤ 106
str contains lower case English alphabets

Company Tags :
Accolite Amazon Microsoft MakeMyTrip 

Topic Tags :
Strings Data Structures  -------------------------------------------------------------------------------- /Difficulty: Medium/Maximum path sum from any node/README.md: -------------------------------------------------------------------------------- 1 |

Maximum path sum from any node

Difficulty Level : Difficulty: Medium


Given a binary tree, the task is to find the maximum path sum. The path may start and end at any node in the tree.

2 |

Examples:

3 |
Input: root[] = [10, 2, 10, 20, 1, N, -25, N, N, N, N, 3, 4]
4 | Output: 42
5 | Explanation: 

Max path sum is represented using green colour nodes in the above binary tree.
6 |
Input: root[] = [-17, 11, 4, 20, -2, 10]
7 | Output: 31
8 | Explanation: 

Max path sum is represented using green colour nodes in the above binary tree.
9 |

Constraints:
1 ≤ number of nodes ≤ 103
-104 ≤ node->data ≤ 104

Company Tags :
Flipkart Google Facebook 

Topic Tags :
Tree Data Structures  -------------------------------------------------------------------------------- /Difficulty: Easy/Move All Zeroes to End/README.md: -------------------------------------------------------------------------------- 1 |

Move All Zeroes to End

Difficulty Level : Difficulty: Easy


Given an array arr[]. Push all the zeros of the given array to the right end of the array while maintaining the order of non-zero elements. Do the mentioned change in the array in place.

2 |

Examples:

3 |
Input: arr[] = [1, 2, 0, 4, 3, 0, 5, 0]
 4 | Output: [1, 2, 4, 3, 5, 0, 0, 0]
 5 | Explanation: There are three 0s that are moved to the end.
 6 | 
7 |
Input: arr[] = [10, 20, 30]
 8 | Output: [10, 20, 30]
 9 | Explanation: No change in array as there are no 0s.
10 | 
11 |
Input: arr[] = [0, 0]
12 | Output: [0, 0]
13 | Explanation: No change in array as there are all 0s.
14 |

Constraints:
1 ≤ arr.size() ≤ 105
0 ≤ arr[i] ≤ 105

Company Tags :
Paytm Amazon Microsoft Samsung SAP Labs Linkedin Bloomberg 

Topic Tags :
Arrays Data Structures  -------------------------------------------------------------------------------- /Difficulty: Easy/Intersection of Two arrays with Duplicate Elements/intersection-of-two-arrays-with-duplicate-elements.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | 6 | // } Driver Code Ends 7 | class Solution { 8 | public: 9 | vector intersectionWithDuplicates(vector& a, vector& b) { 10 | // code here 11 | unordered_set setA(a.begin(), a.end()); 12 | unordered_set result; 13 | for (int num : b) { 14 | if (setA.find(num) != setA.end()) { 15 | result.insert(num); 16 | } 17 | } 18 | return vector(result.begin(), result.end()); 19 | } 20 | }; 21 | 22 | //{ Driver Code Starts. 23 | 24 | int main() { 25 | int t; 26 | cin >> t; 27 | cin.ignore(); 28 | while (t--) { 29 | vector arr1, arr2; 30 | string input; 31 | 32 | // Read first array 33 | getline(cin, input); 34 | stringstream ss(input); 35 | int number; 36 | while (ss >> number) { 37 | arr1.push_back(number); 38 | } 39 | 40 | // Read second array 41 | getline(cin, input); 42 | stringstream ss2(input); 43 | while (ss2 >> number) { 44 | arr2.push_back(number); 45 | } 46 | 47 | Solution ob; 48 | vector res = ob.intersectionWithDuplicates(arr1, arr2); 49 | sort(res.begin(), res.end()); 50 | 51 | if (res.size() == 0) { 52 | cout << "[]" << endl; 53 | } else { 54 | for (auto it : res) 55 | cout << it << " "; 56 | cout << endl; 57 | } 58 | cout << "~" << endl; 59 | } 60 | return 0; 61 | } 62 | // } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Rotate by 90 degree/README.md: -------------------------------------------------------------------------------- 1 |

Rotate by 90 degree

Difficulty Level : Difficulty: Medium


Given a square matrix[][]. The task is to rotate it by 90 degrees in clockwise direction without using any extra space.

2 |

Examples:

3 |
Input: mat[][] = [[1 2 3], [4 5 6], [7 8 9]]
4 | Output:
5 | 7 4 1 
8 5 2
9 6 3
6 |
Input: mat[][] = [1 2], [3 4]
Output:
3 1
4 2
7 |
Input: mat[][] = [[1]]
Output:
1
8 |

Constraints:
1 ≤ mat.size() ≤ 1000
1 <= mat[][] <= 100

Company Tags :
Paytm Zoho Morgan Stanley Amazon Microsoft Samsung Snapdeal D-E-Shaw 

Topic Tags :
Matrix Data Structures  -------------------------------------------------------------------------------- /Difficulty: Hard/Find median in a stream/find-median-in-a-stream.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | 6 | // } Driver Code Ends 7 | 8 | class Solution { 9 | public: 10 | vector getMedian(vector &arr) { 11 | vectorans; 12 | vectorvec; 13 | vec.push_back(arr[0]); 14 | ans.push_back(arr[0]); 15 | for(int i=1;i> t; 43 | cin.ignore(); 44 | while (t--) { 45 | 46 | string s; 47 | getline(cin, s); 48 | stringstream ss(s); 49 | vector nums; 50 | int num; 51 | while (ss >> num) { 52 | nums.push_back(num); 53 | } 54 | Solution ob; 55 | vector ans = ob.getMedian(nums); 56 | cout << fixed << setprecision(1); 57 | for (auto &i : ans) 58 | cout << i << " "; 59 | cout << "\n"; 60 | cout << "~" << endl; 61 | } 62 | return 0; 63 | } 64 | // } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/k largest elements/README.md: -------------------------------------------------------------------------------- 1 |

k largest elements

Difficulty Level : Difficulty: Medium


Given an array arr[] of positive integers and an integer k, Your task is to return k largest elements in decreasing order. 

2 |

Examples:

3 |
Input: arr[] = [12, 5, 787, 1, 23], k = 2
 4 | Output: [787, 23]
 5 | Explanation: 1st largest element in the array is 787 and second largest is 23.
 6 | 
7 |
Input: arr[] = [1, 23, 12, 9, 30, 2, 50], k = 3 
 8 | Output: [50, 30, 23]
 9 | Explanation: Three Largest elements in the array are 50, 30 and 23.
10 |
Input: arr[] = [12, 23], k = 1
11 | Output: [23]
12 | Explanation: 1st Largest element in the array is 23.
13 |

Constraints:
1 ≤ k ≤ arr.size() ≤ 106
1 ≤ arr[i] ≤ 106

 

Company Tags :
Amazon Microsoft Samsung Walmart Google 

Topic Tags :
Arrays Sorting Heap Data Structures Algorithms  -------------------------------------------------------------------------------- /Difficulty: Basic/Count Linked List Nodes/README.md: -------------------------------------------------------------------------------- 1 |

Count Linked List Nodes

Difficulty Level : Difficulty: Basic


Given a singly linked list. The task is to find the length of the linked list, where length is defined as the number of nodes in the linked list.

2 |

Examples :

3 |
Input: LinkedList : 1->2->3->4->5

Output: 5 4 | Explanation: Count of nodes in the linked list is 5, which is its length.
5 |
6 |
Input: LinkedList : 2->4->6->7->5->1->0

Output: 7 7 | Explanation: Count of nodes in the linked list is 7. Hence, the output is 7.
8 |

Expected Time Complexity: O(n)
Expected Auxilliary Space: O(1)

9 |

Constraints:
1 <= number of nodes <= 105
1 <= node->data <= 103


Topic Tags :
Linked List Data Structures  -------------------------------------------------------------------------------- /Difficulty: Easy/Count distinct elements in every window/count-distinct-elements-in-every-window.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | // Initial Template for C++ 3 | #include 4 | using namespace std; 5 | 6 | 7 | // } Driver Code Ends 8 | 9 | class Solution 10 | { 11 | public: 12 | vector countDistinct(vector &arr, int k) 13 | { 14 | // code here. 15 | vector a; 16 | unordered_mapf; 17 | int n = arr.size(); 18 | 19 | for(int i=0;i> t; 50 | cin.ignore(); 51 | while (t--) { 52 | vector arr; 53 | string input; 54 | getline(cin, input); 55 | stringstream ss(input); 56 | int number; 57 | while (ss >> number) { 58 | arr.push_back(number); 59 | } 60 | string ks; 61 | getline(cin, ks); 62 | int k = stoi(ks); 63 | Solution obj; 64 | vector res = obj.countDistinct(arr, k); 65 | for (auto it : res) 66 | cout << it << " "; 67 | cout << endl; 68 | cout << "~" 69 | << "\n"; 70 | } 71 | 72 | return 0; 73 | } 74 | 75 | // } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Easy/Linked List Matrix/linked-list-matrix.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def constructLinkedMatrix(self, mat): 3 | #your code goes here 4 | nodes = [[Node(x) for x in row] for row in mat] 5 | for i in range(len(mat)): 6 | for j in range(len(mat) - 1): 7 | nodes[i][j].right = nodes[i][j + 1] 8 | nodes[j][i].down = nodes[j + 1][i] 9 | return nodes[0][0] 10 | 11 | 12 | #{ 13 | # Driver Code Starts 14 | class Node(): 15 | 16 | def __init__(self, x): 17 | self.data = x 18 | self.right = None 19 | self.down = None 20 | 21 | 22 | def display(head): 23 | Dp = head 24 | while Dp: 25 | Rp = Dp 26 | while Rp: 27 | print(Rp.data, end=" ") 28 | if Rp.right: 29 | print(Rp.right.data, end=" ") 30 | else: 31 | print("null", end=" ") 32 | if Rp.down: 33 | print(Rp.down.data, end=" ") 34 | else: 35 | print("null", end=" ") 36 | Rp = Rp.right 37 | Dp = Dp.down 38 | 39 | 40 | if __name__ == "__main__": 41 | for _ in range(int(input())): 42 | # First row input 43 | a = list(map(int, input().strip().split())) 44 | n = len(a) 45 | 46 | # Input the matrix 47 | mat = [a] 48 | for i in range(1, n): 49 | row = list(map(int, input().strip().split())) 50 | mat.append(row) 51 | 52 | # Create a Solution object and construct the linked matrix 53 | obj = Solution() 54 | head = obj.constructLinkedMatrix(mat) 55 | if head is None: 56 | print(-1) 57 | continue 58 | display(head) 59 | print() 60 | 61 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Easy/Check Equal Arrays/README.md: -------------------------------------------------------------------------------- 1 |

Check Equal Arrays

Difficulty Level : Difficulty: Easy


Given two arrays a[] and b[] of equal size, the task is to find whether the elements in the arrays are equal.

2 |
3 |

Two arrays are said to be equal if both contain the same set of elements, arrangements (or permutations) of elements may be different though.

4 |
5 |

Note: If there are repetitions, then counts of repeated elements must also be the same for two arrays to be equal.

6 |

Examples:

7 |
Input: a[] = [1, 2, 5, 4, 0], b[] = [2, 4, 5, 0, 1]
 8 | Output: true
 9 | Explanation: Both the array can be rearranged to [0,1,2,4,5]
10 | 
11 |
Input: a[] = [1, 2, 5], b[] = [2, 4, 15]
12 | Output: false
13 | Explanation: a[] and b[] have only one common value.
14 |

Constraints:
1<= a.size(), b.size()<=107
0<=a[i], b[i]<=109

Company Tags :
Goldman Sachs 

Topic Tags :
Arrays Hash Sorting Data Structures Algorithms  -------------------------------------------------------------------------------- /Difficulty: Easy/Sort 0s, 1s and 2s/README.md: -------------------------------------------------------------------------------- 1 |

Sort 0s, 1s and 2s

Difficulty Level : Difficulty: Easy


Given an array arr[] containing only 0s, 1s, and 2s. Sort the array in ascending order.

2 |

Examples:

3 |
Input: arr[] = [0, 1, 2, 0, 1, 2]
4 | Output: [0, 0, 1, 1, 2, 2]
5 | Explanation: 0s 1s and 2s are segregated into ascending order.
6 |
Input: arr[] = [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1]
7 | Output: [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2]
8 | Explanation: 0s 1s and 2s are segregated into ascending order.
9 |

Constraints:
1 <= arr.size() <= 106
0 <= arr[i] <= 2

Company Tags :
Paytm Flipkart Morgan Stanley Amazon Microsoft OYO Rooms Samsung Snapdeal Hike MakeMyTrip Ola Cabs Walmart MAQ Software Adobe Yatra.com SAP Labs Qualcomm 

Topic Tags :
Arrays Sorting Data Structures Algorithms  -------------------------------------------------------------------------------- /Difficulty: Easy/Number of occurrence/README.md: -------------------------------------------------------------------------------- 1 |

Number of occurrence

Difficulty Level : Difficulty: Easy


Given a sorted array, arr[] and a number target, you need to find the number of occurrences of target in arr[]

2 |

Examples :

3 |
Input: arr[] = [1, 1, 2, 2, 2, 2, 3], target = 2
 4 | Output: 4
 5 | Explanation: target = 2 occurs 4 times in the given array so the output is 4.
6 |
Input: arr[] = [1, 1, 2, 2, 2, 2, 3], target = 4
 7 | Output: 0
 8 | Explanation: target = 4 is not present in the given array so the output is 0.
9 |
Input: arr[] = [8, 9, 10, 12, 12, 12], target = 12
10 | Output: 3
11 | Explanation: target = 12 occurs 3 times in the given array so the output is 3.
12 |

Constraints:
1 ≤ arr.size() ≤ 106
1 ≤ arr[i] ≤ 106
1 ≤ target ≤ 106

Company Tags :
Zoho Amazon MakeMyTrip 

Topic Tags :
Arrays Searching Data Structures Algorithms  -------------------------------------------------------------------------------- /Difficulty: Easy/Search in a row-wise sorted matrix/README.md: -------------------------------------------------------------------------------- 1 |

Search in a row-wise sorted matrix

Difficulty Level : Difficulty: Easy


Given a row-wise sorted 2D matrix mat[][] of size n x m and an integer x, find whether element x is present in the matrix.
Note: In a row-wise sorted matrix, each row is sorted in itself, i.e. for any i, j within bounds, mat[i][j] <= mat[i][j+1].


Examples :

2 |
Input: mat[][] = [[3, 4, 9],[2, 5, 6],[9, 25, 27]], x = 9
 3 | Output: true
 4 | Explanation: 9 is present in the matrix, so the output is true.
 5 | 
6 |
Input: mat[][] = [[19, 22, 27, 38, 55, 67]], x = 56
Output: false 7 | Explanation: 56 is not present in the matrix, so the output is false.
8 |
Input: mat[][] = [[1, 2, 9],[65, 69, 75]], x = 91
Output: false 9 | Explanation: 91 is not present in the matrix.
10 |

Constraints:
1 <= n, m <= 1000
1 <= mat[i][j] <= 105
1 <= x <= 105


Topic Tags :
Binary Search Arrays Matrix  -------------------------------------------------------------------------------- /Difficulty: Medium/Quick Sort on Linked List/README.md: -------------------------------------------------------------------------------- 1 |

Quick Sort on Linked List

Difficulty Level : Difficulty: Medium


You are given a Linked List. Sort the given Linked List using quicksort

2 |

Examples:

3 |
Input: Linked list: 1->6->2
Output: 1->2->6

Explanation:

After sorting the nodes, we have 1, 2 and 6.
4 |
Input: Linked list: 1->9->3->8
Output: 1->3->8->9

Explanation:
After sorting the nodes, we have 1, 3, 8 and 9.
5 |

Constraints:
1<= size of linked list <= 105

Company Tags :
Paytm 

Topic Tags :
Linked List Data Structures  -------------------------------------------------------------------------------- /Difficulty: Basic/Java Switch Case statement/java-switch-case-statement.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | 6 | class Array 7 | { 8 | public: 9 | template 10 | static void input(vector &A,int n) 11 | { 12 | for (int i = 0; i < n; i++) 13 | { 14 | scanf("%lf ",&A[i]); 15 | } 16 | } 17 | 18 | template 19 | static void print(vector &A) 20 | { 21 | cout< &arr) { 36 | // code here 37 | switch(choice){ 38 | case 1 : return 3.14159*arr[0] * arr[0]; 39 | 40 | case 2 : return arr[0] * arr[1]; 41 | 42 | default: return -1; 43 | 44 | } 45 | } 46 | }; 47 | 48 | 49 | //{ Driver Code Starts. 50 | 51 | int main(){ 52 | int t; 53 | scanf("%d ",&t); 54 | while(t--){ 55 | 56 | int choice; 57 | scanf("%d",&choice); 58 | 59 | 60 | vector arr(choice); 61 | Array::input(arr,choice); 62 | 63 | Solution obj; 64 | double res = obj.switchCase(choice, arr); 65 | // cout<Count Smaller elements

Difficulty Level : Difficulty: Hard


Given an array arr containing non-negative integers. Count and return an array ans where ans[i] denotes the number of smaller elements on right side of arr[i].

2 |

Examples:

3 |
Input: arr[] = [12, 1, 2, 3, 0, 11, 4]
 4 | Output: [6, 1, 1, 1, 0, 1, 0]
 5 | Explanation: There are 6 smaller elements right after 12. There is 1 smaller element right after 1. And so on.
 6 | 
7 |
Input: arr[] = [1, 2, 3, 4, 5]
 8 | Output: [0, 0, 0, 0, 0]
 9 | Explanation: There are 0 smaller elements right after 1. There are 0 smaller elements right after 2. And so on.
10 | 
11 |

Expected Time Complexity: O(n*logn)
Expected Auxiliary Space: O(n)

12 |

Constraints:
1 ≤ arr.size() ≤ 106
0 ≤ arr[i]  ≤ 108

Company Tags :
Google Codenation 

Topic Tags :
Arrays Sorting Binary Search Data Structures Algorithms  -------------------------------------------------------------------------------- /Difficulty: Medium/Find All Triplets with Zero Sum/find-all-triplets-with-zero-sum.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | 6 | // } Driver Code Ends 7 | // User function Template for C++ 8 | #include 9 | #include 10 | using namespace std; 11 | 12 | class Solution { 13 | public: 14 | vector> findTriplets(vector &arr) { 15 | vector> result; 16 | int n = arr.size(); 17 | 18 | // Iterate over the array to find triplets 19 | for (int i = 0; i < n - 2; i++) { 20 | for (int j = i + 1; j < n - 1; j++) { 21 | for (int k = j + 1; k < n; k++) { 22 | if (arr[i] + arr[j] + arr[k] == 0) { 23 | result.push_back({i, j, k}); 24 | } 25 | } 26 | } 27 | } 28 | 29 | return result; 30 | } 31 | }; 32 | 33 | //{ Driver Code Starts. 34 | 35 | int main() { 36 | int t; 37 | cin >> t; 38 | cin.ignore(); 39 | while (t--) { 40 | vector arr; 41 | string input; 42 | getline(cin, input); 43 | stringstream ss(input); 44 | int number; 45 | while (ss >> number) { 46 | arr.push_back(number); 47 | } 48 | Solution ob; 49 | 50 | vector> res = ob.findTriplets(arr); 51 | sort(res.begin(), res.end()); 52 | if (res.size() == 0) { 53 | cout << "[]\n"; 54 | } 55 | for (int i = 0; i < res.size(); i++) { 56 | for (int j = 0; j < res[i].size(); j++) { 57 | cout << res[i][j] << " "; 58 | } 59 | cout << endl; 60 | } 61 | cout << "~" << endl; 62 | } 63 | return 0; 64 | } 65 | // } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Smallest Positive Missing Number/README.md: -------------------------------------------------------------------------------- 1 |

Smallest Positive Missing Number

Difficulty Level : Difficulty: Medium


You are given an integer array arr[]. Your task is to find the smallest positive number missing from the array.

2 |

Note: Positive number starts from 1. The array can have negative integers too.

3 |

Examples:

4 |
Input: arr[] = [2, -3, 4, 1, 1, 7]
 5 | Output: 3
 6 | Explanation: Smallest positive missing number is 3.
 7 | 
8 |
Input: arr[] = [5, 3, 2, 5, 1]
 9 | Output: 4
10 | Explanation: Smallest positive missing number is 4.
11 |
Input: arr[] = [-8, 0, -1, -4, -3]
12 | Output: 1
13 | Explanation: Smallest positive missing number is 1.
14 |

Constraints:  
1 <= arr.size() <= 105
-106 <= arr[i] <= 106

Company Tags :
Accolite Amazon Samsung Snapdeal 

Topic Tags :
Arrays Searching Data Structures Algorithms  -------------------------------------------------------------------------------- /Difficulty: Easy/Reorganize The Array/README.md: -------------------------------------------------------------------------------- 1 |

Reorganize The Array

Difficulty Level : Difficulty: Easy


Given an array of elements arr[] with indices ranging from 0 to arr.size() - 1, your task is to write a program that rearranges the elements of the array such that arr[i] = i. If an element i is not present in the array, -1 should be placed at the corresponding index.

2 |

Examples:

3 |
Input: arr[] = [-1, -1, 6, 1, 9, 3, 2, -1, 4, -1]
 4 | Output: [-1, 1, 2, 3, 4, -1, 6, -1, -1, 9]
 5 | Explanation: Here We can see there are 10 elements. So, the sorted array will look like [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] but in our array we are not having 0, 5, 7 and 8. So, at there places we will be printing -1 and otherplaces will be having elements.
6 |
Input: arr[] = [2, 0, 1]
 7 | Output: [0, 1, 2]
 8 | Explanation: Here We can see all the elements are present so no -1 is returned in array.
 9 | 
10 |

Expected Time Complexity: O(n).
Expected Auxiliary Space: O(1).

11 |

Constraints:
0 ≤ arr.size() ≤ 105
-1 ≤ arr[i] ≤ arr.size()-1


Topic Tags :
Arrays Data Structures  -------------------------------------------------------------------------------- /Difficulty: Medium/Search Pattern (KMP-Algorithm)/search-pattern-kmpalgorithm.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class Solution: 4 | def search(self, pat, txt): 5 | def computeLPSArray(pat): 6 | lps = [0] * len(pat) 7 | length = 0 8 | i = 1 9 | while i < len(pat): 10 | if pat[i] == pat[length]: 11 | length += 1 12 | lps[i] = length 13 | i += 1 14 | else: 15 | if length != 0: 16 | length = lps[length - 1] 17 | else: 18 | lps[i] = 0 19 | i += 1 20 | return lps 21 | 22 | m = len(pat) 23 | n = len(txt) 24 | lps = computeLPSArray(pat) 25 | 26 | i = 0 27 | j = 0 28 | result = [] 29 | 30 | while i < n: 31 | if pat[j] == txt[i]: 32 | i += 1 33 | j += 1 34 | 35 | if j == m: 36 | result.append(i - j) 37 | j = lps[j - 1] 38 | elif i < n and pat[j] != txt[i]: 39 | if j != 0: 40 | j = lps[j - 1] 41 | else: 42 | i += 1 43 | 44 | return result 45 | # code here 46 | 47 | 48 | #{ 49 | # Driver Code Starts 50 | #Initial Template for Python 3 51 | 52 | if __name__ == '__main__': 53 | t = int(input()) 54 | for _ in range(t): 55 | s = input().strip() 56 | patt = input().strip() 57 | ob = Solution() 58 | ans = ob.search(patt, s) 59 | if len(ans) == 0: 60 | print("[]", end="") 61 | for value in ans: 62 | print(value, end=' ') 63 | print() 64 | 65 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Find triplets with zero sum/README.md: -------------------------------------------------------------------------------- 1 |

Find triplets with zero sum

Difficulty Level : Difficulty: Medium


Given an array arr[] of n integers. Check whether it contains a triplet that sums up to zero. Return true, if there is at least one triplet following the condition else return false.

2 |

Examples:

3 |
Input: n = 5, arr[] = {0, -1, 2, -3, 1}
Output: 1 4 | Explanation: 0, -1, and 1 form a triplet with a sum equal to 0.
5 |
Input: n = 3, arr[] = {1, 2, 3}
Output: 0 6 | Explanation: No triplet with zero sum exists.
7 |

Expected Time Complexity: O(n2)
Expected Auxiliary Space: O(1)

Constraints:
1 <= n <= 104

-106 <= arr[i] <= 106

Company Tags :
Amazon Google Facebook 

Topic Tags :
two-pointer-algorithm Arrays Searching Hash Sorting Data Structures Algorithms  -------------------------------------------------------------------------------- /Difficulty: Easy/Palindrome/README.md: -------------------------------------------------------------------------------- 1 |

Palindrome

Difficulty Level : Difficulty: Easy


You are given an integer n. Your task is to determine whether it is a palindrome.

2 |
3 |

A number is considered a palindrome if it reads the same backward as forward, like the string examples "MADAM" or "MOM".

4 |
5 |

Examples:

6 |
Input: n = 555
 7 | Output: true
Explanation: The number 555 reads the same backward as forward, so it is a palindrome.
8 |
Input: n = 123
 9 | Output: false
Explanation: The number 123 reads differently backward (321), so it is not a palindrome.
10 |
Input: n = 1221
11 | Output: true
12 |

Constraints:
1 ≤ n ≤ 109

Company Tags :
Zoho Samsung Oracle Adobe 

Topic Tags :
palindrome  -------------------------------------------------------------------------------- /Difficulty: Medium/Longest Consecutive Subsequence/README.md: -------------------------------------------------------------------------------- 1 |

Longest Consecutive Subsequence

Difficulty Level : Difficulty: Medium


Given an array arr[] of non-negative integers. Find the length of the longest sub-sequence such that elements in the subsequence are consecutive integers, the consecutive numbers can be in any order.

2 |

Examples:

3 |
Input: arr[] = [2, 6, 1, 9, 4, 5, 3]
 4 | Output: 6
 5 | Explanation: The consecutive numbers here are 1, 2, 3, 4, 5, 6. These 6 numbers form the longest consecutive subsquence.
6 |
Input: arr[] = [1, 9, 3, 10, 4, 20, 2]
 7 | Output: 4
 8 | Explanation: 1, 2, 3, 4 is the longest consecutive subsequence.
9 |
Input: arr[] = [15, 13, 12, 14, 11, 10, 9]
10 | Output: 7
11 | Explanation: The longest consecutive subsequence is 9, 10, 11, 12, 13, 14, 15, which has a length of 7.
12 | 
13 |

Constraints:
1 <= arr.size() <= 105
0 <= arr[i] <= 105

Company Tags :
Amazon Microsoft Walmart 

Topic Tags :
Hash Data Structures  -------------------------------------------------------------------------------- /Difficulty: Hard/N-Queen Problem/nqueen-problem.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | 3 | class Solution: 4 | def nQueen(self, n): 5 | 6 | def get_diagonal(row, col): 7 | return n - 1 - col + row 8 | 9 | def get_antidiagonal(row, col): 10 | return col + row 11 | 12 | # True values indicate these aren't used yet 13 | rows = [True] * n 14 | diagonals = [True] * (2 * n - 1) 15 | antidiagonals = [True] * (2 * n - 1) 16 | 17 | def dfs(col=0, acc=[], paths=[]): 18 | if col == n: 19 | paths.append(acc.copy()) 20 | return paths 21 | for row in range(n): 22 | d = get_diagonal(row, col) 23 | ad = get_antidiagonal(row, col) 24 | if rows[row] and diagonals[d] and antidiagonals[ad]: 25 | rows[row] = diagonals[d] = antidiagonals[ad] = False 26 | acc.append(row + 1) 27 | dfs(col + 1) 28 | acc.pop() 29 | rows[row] = diagonals[d] = antidiagonals[ad] = True 30 | return paths 31 | 32 | return dfs() 33 | 34 | #{ 35 | # Driver Code Starts 36 | #Initial Template for Python 3 37 | 38 | if __name__ == '__main__': 39 | t = int(input()) 40 | for _ in range(t): 41 | n = int(input()) 42 | 43 | ob = Solution() 44 | ans = ob.nQueen(n) 45 | if (len(ans) == 0): 46 | print("-1") 47 | else: 48 | ans.sort() 49 | for i in range(len(ans)): 50 | print("[", end="") 51 | for j in range(len(ans[i])): 52 | print(ans[i][j], end=" ") 53 | print("]", end=" ") 54 | print() 55 | 56 | print("~") 57 | 58 | # } Driver Code Ends -------------------------------------------------------------------------------- /Difficulty: Medium/Merge two BST 's/README.md: -------------------------------------------------------------------------------- 1 |

Merge two BST 's

Difficulty Level : Difficulty: Medium


Given two BSTs, return elements of merged BSTs in sorted form.

2 |

Examples :

3 |
Input:
 4 | BST1:
 5 |        5
 6 |      /   \
 7 |     3     6
 8 |    / \
 9 |   2   4  
10 | BST2:
11 |         2
12 |       /   \
13 |      1     3
14 |             \
15 |              7
16 |             /
17 |            6
18 | Output: 1 2 2 3 3 4 5 6 6 7
19 | Explanation: After merging and sorting the two BST we get 1 2 2 3 3 4 5 6 6 7.
20 | 
21 |
Input:
22 | BST1:
23 |        12
24 |      /   
25 |     9
26 |    / \    
27 |   6   11
28 | BST2:
29 |       8
30 |     /  \
31 |    5    10
32 |   /
33 |  2
34 | Output: 2 5 6 8 9 10 11 12
35 | Explanation: After merging and sorting the two BST we get 2 5 6 8 9 10 11 12.
36 |

Expected Time Complexity: O((m+n)*log(m+n))
Expected Auxiliary Space: O(Height of BST1 + Height of BST2 + m + n)

37 |

Constraints:
1 ≤ Number of Nodes, value of nodes ≤ 105


Topic Tags :
Binary Search Tree Tree Data Structures  -------------------------------------------------------------------------------- /Difficulty: Easy/Prime Number/README.md: -------------------------------------------------------------------------------- 1 |

Prime Number

Difficulty Level : Difficulty: Easy


Given a number n, determine whether it is a prime number or not.
Note: A prime number is a number greater than 1 that has no positive divisors other than 1 and itself.

2 |

Examples :

3 |
Input: n = 7
 4 | Output: true
 5 | Explanation: 7 has exactly two divisors: 1 and 7, making it a prime number.
6 |
Input: n = 25
 7 | Output: false
 8 | Explanation: 25 has more than two divisors: 1, 5, and 25, so it is not a prime number.
9 |
Input: n = 1
10 | Output: false
11 | Explanation: 1 has only one divisor (1 itself), which is not sufficient for it to be considered prime.
12 |

Constraints:
1 ≤ n ≤ 109

Company Tags :
VMWare Amazon SAP Labs 

Topic Tags :
Mathematical Prime Number Algorithms  -------------------------------------------------------------------------------- /Difficulty: Medium/Make array elements unique/README.md: -------------------------------------------------------------------------------- 1 |

Make array elements unique

Difficulty Level : Difficulty: Medium


Given an array arr[ ], your task is to find the minimum number of increment operations required to make all the elements of the array unique. i.e.- no value in the array should occur more than once. In one operation, a value can be incremented by 1 only.

2 |

Examples :

3 |
Input: arr[] = [1, 2, 2]
 4 | Output: 1
 5 | Explanation: If we increase arr[2] by 1 then the resulting array becomes {1, 2, 3} and has all unique values.Hence, the answer is 1 in this case.
6 |
Input: arr[] = [1, 1, 2, 3]
 7 | Output: 3
 8 | Explanation: If we increase arr[0] by 3, then all array elements will be unique. Hence, the answer is 3 in this case.
9 |
Input: arr[] = [5, 4, 3, 2, 1]
10 | Output: 0
11 | Explanation: All elements are unique.
12 |

Constraints:
1 ≤ arr.size() ≤ 106
0 ≤ arr[i] ≤ 106

Company Tags :
Dunzo 

Topic Tags :
Arrays Hash Sorting Data Structures Algorithms  -------------------------------------------------------------------------------- /Difficulty: Medium/Overlapping Intervals/README.md: -------------------------------------------------------------------------------- 1 |

Overlapping Intervals

Difficulty Level : Difficulty: Medium


Given an array of Intervals arr[][], where arr[i] = [starti, endi]. The task is to merge all of the overlapping Intervals.

2 |

Examples:

3 |
Input: arr[][] = [[1,3],[2,4],[6,8],[9,10]]
4 | Output: [[1,4], [6,8], [9,10]]
5 | Explanation: In the given intervals we have only two overlapping intervals here, [1,3] and [2,4] which on merging will become [1,4]. Therefore we will return [[1,4], [6,8], [9,10]].
6 | 
7 |
Input: arr[][] = [[6,8],[1,9],[2,4],[4,7]]
8 | Output: [[1,9]]
Explanation: In the given intervals all the intervals overlap with the interval [1,9]. Therefore we will return [1,9].
9 |

Constraints:
1 ≤ arr.size() ≤ 105
0 ≤ starti ≤ endi ≤ 105

Company Tags :
Amazon Microsoft Google Nutanix 

Topic Tags :
Arrays Hash Sorting Data Structures Algorithms  --------------------------------------------------------------------------------