├── .editorconfig ├── .vscode └── settings.json ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── Companywise Questions └── README.MD ├── DSA Crack Sheet ├── README.md └── solutions │ ├── AGGRCOW - Aggressive cows.cpp │ ├── Add 1 to a number represented as linked list.cpp │ ├── Add two numbers represented by linked lists.cpp │ ├── Allocate minimum number of pages.cpp │ ├── Array Subset of another array.cpp │ ├── Best Time to Buy and Sell Stock III.cpp │ ├── Best Time to Buy and Sell Stock.cpp │ ├── Binary Tree to BST.cpp │ ├── Binary Tree to DLL.cpp │ ├── Bishu and Soldiers.cpp │ ├── Bottom View of Binary Tree.cpp │ ├── Boundary Traversal of binary tree.cpp │ ├── Brothers From Different Roots.cpp │ ├── Capacity To Ship Packages Within D Days.cpp │ ├── Check If Circular Linked List.cpp │ ├── Check Mirror in N-ary tree.cpp │ ├── Check for BST.cpp │ ├── Check for Balanced Tree.cpp │ ├── Check if Linked List is Palindrome.cpp │ ├── Check if Tree is Isomorphic.cpp │ ├── Check if strings are rotations of each other or not.cpp │ ├── Check whether BST contains Dead End.cpp │ ├── Chocolate Distribution Problem.cpp │ ├── Choose and Swap.cpp │ ├── Circular tour.cpp │ ├── Clone a linked list with next and random pointer.cpp │ ├── Combination Sum.cpp │ ├── Common elements.cpp │ ├── Construct Tree from Inorder & Preorder.cpp │ ├── Convert BST to Min Heap.cpp │ ├── Count BST nodes that lie in a given range.cpp │ ├── Count Inversions.cpp │ ├── Count Palindromic Subsequences.cpp │ ├── Count Squares.cpp │ ├── Count and Say.cpp │ ├── Count pairs with given sum.cpp │ ├── Count the Reversals.cpp │ ├── Count triplets with sum smaller than X.cpp │ ├── Cyclically rotate an array by one.cpp │ ├── Delete Node in a BST.cpp │ ├── Delete nodes having greater value on right.cpp │ ├── Detect Loop in linked list.cpp │ ├── Diagonal Traversal of Binary Tree.cpp │ ├── Diameter of Binary Tree.cpp │ ├── Distance of nearest cell having 1.cpp │ ├── Duplicate Subtrees.cpp │ ├── Duplicate subtree in Binary Tree.cpp │ ├── Edit Distance.cpp │ ├── Equivalent numeric keypad sequence.cpp │ ├── Evaluation of Postfix Expression.cpp │ ├── Factorials of large numbers.cpp │ ├── Find All Four Sum Numbers.cpp │ ├── Find Minimum in Rotated Sorted Array.cpp │ ├── Find Missing And Repeating.cpp │ ├── Find Pair Given Difference.cpp │ ├── Find median in a stream.cpp │ ├── Find the Duplicate Number.cpp │ ├── Find the string in grid.cpp │ ├── First and last occurrences of X.cpp │ ├── First negative integer in every window of size k.cpp │ ├── First non-repeating character in a stream.cpp │ ├── Flattening a Linked List.cpp │ ├── Fractional Knapsack.cpp │ ├── Game with String.cpp │ ├── Given a linked list of 0s, 1s and 2s, sort it.cpp │ ├── Heap Sort.cpp │ ├── Height of Binary Tree.cpp │ ├── Huffman Encoding.cpp │ ├── Implement Queue using array.cpp │ ├── Implement stack using array.cpp │ ├── Implement two stacks in an array.cpp │ ├── Intersection Point in Y Shapped Linked Lists.cpp │ ├── Intersection of two sorted Linked lists.cpp │ ├── Is Binary Tree Heap.cpp │ ├── Job Sequencing Problem.cpp │ ├── K-th element of two sorted Arrays.cpp │ ├── Kadane's Algorithm.cpp │ ├── Kth element in Matrix.cpp │ ├── Kth largest element in BST.cpp │ ├── Kth smallest element.cpp │ ├── Kth smallest number again.cpp │ ├── LRU Cache.cpp │ ├── Largest BST.cpp │ ├── Largest number in K swaps.cpp │ ├── Leaf at same level.cpp │ ├── Left View of Binary Tree.cpp │ ├── Level order traversal.cpp │ ├── Longest Common Prefix.cpp │ ├── Longest Common Subsequence.cpp │ ├── Longest Palindromic Substring.cpp │ ├── Longest Prefix Suffix.cpp │ ├── Longest Repeating Subsequence.cpp │ ├── Longest consecutive subsequence.cpp │ ├── Lowest Common Ancestor in a BST.cpp │ ├── Lowest Common Ancestor in a Binary Tree.cpp │ ├── M-Coloring Problem.cpp │ ├── Majority Element.cpp │ ├── Max rectangle.cpp │ ├── Maximum Product Subarray.cpp │ ├── Maximum Rectangular Area in a Histogram.cpp │ ├── Maximum of all subarrays of size k.cpp │ ├── Median in a row-wise sorted Matrix.cpp │ ├── Merge Intervals.cpp │ ├── Merge K sorted linked lists.cpp │ ├── Merge Sort for Linked List.cpp │ ├── Merge Without Extra Space.cpp │ ├── Merge k Sorted Arrays.cpp │ ├── Merge two binary Max heaps.cpp │ ├── Mid Element Stack.cpp │ ├── Middle of Three.cpp │ ├── Middle of the Linked List.cpp │ ├── Min Number of Flips.cpp │ ├── Min distance between two given nodes of a Binary Tree.cpp │ ├── Minimum Cost of ropes.cpp │ ├── Minimum Swaps for Bracket Balancing.cpp │ ├── Minimum Swaps to Sort.cpp │ ├── Minimum element in BST.cpp │ ├── Minimum number of jumps.cpp │ ├── Minimum sum.cpp │ ├── Minimum swaps and K together.cpp │ ├── Multiply two linked lists.cpp │ ├── N meetings in one room.cpp │ ├── N-Queens II.cpp │ ├── N-Queens.cpp │ ├── Next Greater Element.cpp │ ├── Next Permutation.cpp │ ├── Nth node from end of linked list.cpp │ ├── Palindrome Partitioning.cpp │ ├── Palindrome String.cpp │ ├── Parenthesis Checker.cpp │ ├── Partition Equal Subset Sum.cpp │ ├── Partition array to K subsets.cpp │ ├── Permutations of a given string.cpp │ ├── Populate Inorder Successor for all nodes.cpp │ ├── Predecessor and Successor.cpp │ ├── Preorder to BST.cpp │ ├── Print Anagrams Together.cpp │ ├── Product array puzzle.cpp │ ├── Queue Reversal.cpp │ ├── Queue using two Stacks.cpp │ ├── Quick Sort on Linked List.cpp │ ├── Rat in a Maze Problem.cpp │ ├── Rearrange array in alternating positive & negative items with O(1) extra space.cpp │ ├── Rearrange characters.cpp │ ├── Remove Consecutive Characters.cpp │ ├── Remove Invalid Parentheses.cpp │ ├── Remove duplicate element from sorted Linked List.cpp │ ├── Remove duplicates from an unsorted linked list.cpp │ ├── Remove loop in Linked List.cpp │ ├── Reorganize String.cpp │ ├── Reverse First K elements of Queue.cpp │ ├── Reverse Level Order Traversal.cpp │ ├── Reverse String.cpp │ ├── Reverse a Doubly Linked List.cpp │ ├── Reverse a Linked List in groups of given size.cpp │ ├── Reverse a linked list.cpp │ ├── Reverse a string using Stack.cpp │ ├── Right View of Binary Tree.cpp │ ├── Roman Number to Integer.cpp │ ├── Rotten Oranges.cpp │ ├── Row with max 1s.cpp │ ├── Search a 2D Matrix.cpp │ ├── Search in Rotated Sorted Array.cpp │ ├── Second most repeated string in a sequence.cpp │ ├── Segregate even and odd nodes in a Link List.cpp │ ├── Smallest distinct window.cpp │ ├── Smallest range in K lists.cpp │ ├── Smallest subarray with sum greater than x.cpp │ ├── Sort a stack.cpp │ ├── Sort an array of 0s, 1s and 2s.cpp │ ├── Sort by Set Bit Count.cpp │ ├── Sorted matrix.cpp │ ├── Special Stack.cpp │ ├── Spirally traversing a matrix.cpp │ ├── Split a Circular Linked List into two halves.cpp │ ├── Stack using two queues.cpp │ ├── Stickler Thief.cpp │ ├── Subarray with 0 sum.cpp │ ├── Sudoku Solver.cpp │ ├── Sum Tree.cpp │ ├── Sum of the Longest Bloodline of a Tree.cpp │ ├── The Celebrity Problem.cpp │ ├── Three way partitioning.cpp │ ├── Top View of Binary Tree.cpp │ ├── Transform to Sum Tree.cpp │ ├── Trapping Rain Water.cpp │ ├── Triplet Sum in Array.cpp │ ├── Union of two arrays.cpp │ ├── Valid Substring.cpp │ ├── Value equal to index value.cpp │ ├── Word Break - Part 2.cpp │ ├── Word Break.cpp │ ├── Zero Sum Subarrays.cpp │ ├── ZigZag Tree Traversal.cpp │ ├── k largest elements.cpp │ └── k-th smallest element in BST.cpp ├── LICENSE ├── Leetcode Daily Challenge ├── April-2021 │ ├── 01. Palindrome Linked List.cpp │ ├── 02. Ones and Zeroes.cpp │ ├── 03. Longest Valid Parentheses.cpp │ ├── 04. Design Circular Queue.cpp │ ├── 05. Global and Local Inversions.cpp │ ├── 06. Minimum Operations to Make Array Equal.cpp │ ├── 07. Determine if String Halves Are Alike.cpp │ ├── 08. Letter Combinations of a Phone Number.cpp │ ├── 09. Verifying an Alien Dictionary.cpp │ ├── 10. Longest Increasing Path in a Matrix.cpp │ ├── 11. Deepest Leaves Sum.cpp │ ├── 12. Beautiful Arrangement II.cpp │ ├── 13. Flatten Nested List Iterator.cpp │ ├── 14. Partition List.cpp │ ├── 15. Fibonacci Number.cpp │ ├── 16. Remove All Adjacent Duplicates in String II.cpp │ ├── 17. Number of Submatrices That Sum to Target.cpp │ ├── 18. Remove Nth Node From End of List.cpp │ ├── 19. Combination Sum IV.cpp │ ├── 20. N-ary Tree Preorder Traversal.cpp │ ├── 21. Triangle.cpp │ ├── 22. Brick Wall.cpp │ ├── 23. Count Binary Substrings.cpp │ ├── 25. Rotate Image.cpp │ ├── 26. Furthest Building You Can Reach.cpp │ ├── 27. Power of Three.cpp │ ├── 28. Unique Paths II.cpp │ ├── 29. Find First and Last Position of Element in Sorted Array.cpp │ ├── 30. Powerful Integers.cpp │ └── README.md ├── August-2021 │ ├── 01. Making A Large Island.cpp │ ├── 02. Two Sum.cpp │ ├── 03. Subsets II.cpp │ ├── 04. Path Sum II.cpp │ ├── 05. Stone Game.cpp │ ├── 06. N-ary Tree Level Order Traversal.cpp │ ├── 07. Palindrome Partitioning II.cpp │ ├── 09. Add Strings.cpp │ ├── 10. Flip String to Monotone Increasing.cpp │ ├── 11. Array of Doubled Pairs.cpp │ ├── 12. Group Anagrams.cpp │ ├── 13. Set Matrix Zeroes.cpp │ ├── 15. Minimum Window Substring.cpp │ ├── 16. Range Sum Query - Immutable.cpp │ ├── 17. Count Good Nodes in Binary Tree.cpp │ ├── 18. Decode Ways.cpp │ ├── 19. Maximum Product of Splitted Binary Tree.cpp │ ├── 20. Valid Sudoku.cpp │ ├── 21. Sudoku Solver.cpp │ ├── 23. Two Sum IV - Input is a BST.cpp │ ├── 24. Complex Number Multiplication.cpp │ ├── 25. Sum of Square Numbers.cpp │ ├── 26. Verify Preorder Serialization of a Binary Tree.cpp │ ├── 27. Longest Uncommon Subsequence II.cpp │ ├── 28. Maximum Profit in Job Scheduling.cpp │ ├── 30. Range Addition II.cpp │ ├── 31. Find Minimum in Rotated Sorted Array.cpp │ ├── Equal Tree Partition.cpp │ ├── Graph Valid Tree.cpp │ ├── Optimize Water Distribution in a Village.cpp │ ├── Paint Fence.cpp │ ├── Paint House II.cpp │ └── README.md ├── December-2020 │ ├── 01. Maximum Depth of Binary Tree.cpp │ ├── 02. Linked List Random Node.cpp │ ├── 03. Increasing Order Search Tree.cpp │ ├── 04. The kth Factor of n.cpp │ ├── 05. Can Place Flowers.cpp │ ├── 06. Populating Next Right Pointers in Each Node II.cpp │ ├── 07. Spiral Matrix II.cpp │ ├── 08. Pairs of Songs With Total Durations Divisible by 60.cpp │ ├── 09. Binary Search Tree Iterator.cpp │ ├── 10. Valid Mountain Array.cpp │ ├── 11. Remove Duplicates from Sorted Array II.cpp │ ├── 12. Smallest Subtree with all the Deepest Nodes.cpp │ ├── 13. Burst Balloons.cpp │ ├── 14. Palindrome Partitioning.cpp │ ├── 15. Squares of a Sorted Array.cpp │ ├── 16. Validate Binary Search Tree.cpp │ ├── 17. 4Sum II.cpp │ ├── 18. Increasing Triplet Subsequence.cpp │ ├── 19. Cherry Pickup II.cpp │ ├── 20. Decoded String at Index.cpp │ ├── 21. Smallest Range II.cpp │ ├── 22. Balanced Binary Tree.cpp │ ├── 23. Next Greater Element III.cpp │ ├── 24. Swap Nodes in Pairs.cpp │ ├── 25. Diagonal Traverse.cpp │ ├── 26. Decode Ways.cpp │ ├── 27. Jump Game IV.cpp │ ├── 28. Reach a Number.cpp │ ├── 29. Pseudo-Palindromic Paths in a Binary Tree.cpp │ ├── 30. Game of Life.cpp │ ├── 31. Largest Rectangle in Histogram.cpp │ └── README.md ├── February-2021 │ ├── 01. Number of 1 Bits.cpp │ ├── 02. Trim a Binary Search Tree.cpp │ ├── 03. Linked List Cycle.cpp │ ├── 04. Longest Harmonious Subsequence.cpp │ ├── 05. Simplify Path.cpp │ ├── 06. Binary Tree Right Side View.cpp │ ├── 07. Shortest Distance to a Character.cpp │ ├── 08. Peeking Iterator.cpp │ ├── 09. Convert BST to Greater Tree.cpp │ ├── 10. Copy List with Random Pointer.cpp │ ├── 11. Valid Anagram.cpp │ ├── 12. Number of Steps to Reduce a Number to Zero.cpp │ ├── 13. Shortest Path in Binary Matrix.cpp │ ├── 14. Is Graph Bipartite.cpp │ ├── 15. The K Weakest Rows in a Matrix.cpp │ ├── 16. Letter Case Permutation.cpp │ ├── 17. Container With Most Water.cpp │ ├── 18. Arithmetic Slices.cpp │ ├── 19. Minimum Remove to Make Valid Parentheses.cpp │ ├── 20. Roman to Integer.cpp │ ├── 21. Broken Calculator.cpp │ ├── 22. Longest Word in Dictionary through Deleting.cpp │ ├── 23. Search a 2D Matrix II.cpp │ ├── 24. Score of Parentheses.cpp │ ├── 25. Shortest Unsorted Continuous Subarray.cpp │ ├── 26. Validate Stack Sequences.cpp │ ├── 27. Divide Two Integers.cpp │ ├── Maximum Frequency Stack.cpp │ └── README.MD ├── January-2021 │ ├── 01. Check Array Formation Through Concatenation.cpp │ ├── 02. Find a Corresponding Node of a Binary Tree in a Clone of That Tree.cpp │ ├── 03. Beautiful Arrangement.cpp │ ├── 04. Merge Two Sorted Lists.cpp │ ├── 05. Remove Duplicates from Sorted List II.cpp │ ├── 06. Kth Missing Positive Number.cpp │ ├── 07. Longest Substring Without Repeating Characters.cpp │ ├── 08. Check If Two String Arrays are Equivalent.cpp │ ├── 09. Word Ladder.cpp │ ├── 10. Create Sorted Array through Instructions.cpp │ ├── 11. Merge Sorted Array.cpp │ ├── 12. Add Two Numbers.cpp │ ├── 13. Boats to Save People.cpp │ ├── 14. Minimum Operations to Reduce X to Zero.cpp │ ├── 15. Get Maximum in Generated Array.cpp │ ├── 16. Kth Largest Element in an Array.cpp │ ├── 17. Count Sorted Vowel Strings.cpp │ ├── 18. Max Number of K-Sum Pairs.cpp │ ├── 19. Longest Palindromic Substring.cpp │ ├── 20. Valid Parentheses.cpp │ ├── 21. Find the Most Competitive Subsequence.cpp │ ├── 22. Determine if Two Strings Are Close.cpp │ ├── 23. Sort the Matrix Diagonally.cpp │ ├── 24. Merge k Sorted Lists.cpp │ ├── 25. 1's Are at Least Length K Places Away.cpp │ ├── 26. Path With Minimum Effort.cpp │ ├── 27. Concatenation of Consecutive Binary Numbers.cpp │ ├── 28. Smallest String With A Given Numeric Value.cpp │ ├── 29. Vertical Order Traversal of a Binary Tree.cpp │ ├── 30. Minimize Deviation in Array.cpp │ ├── 31. Next Permutation.cpp │ └── README.md ├── July-2021 │ ├── 01. Gray Code.cpp │ ├── 02. Find K Closest Elements.cpp │ ├── 04. Count Vowels Permutation.cpp │ ├── 05. Reshape the Matrix.cpp │ ├── 06. Reduce Array Size to The Half.cpp │ ├── 07. Kth Smallest Element in a Sorted Matrix.cpp │ ├── 08. Maximum Length of Repeated Subarray.cpp │ ├── 09. Longest Increasing Subsequence.cpp │ ├── 10. Decode Ways II.cpp │ ├── 11. Find Median from Data Stream.cpp │ ├── 12. Isomorphic Strings.cpp │ ├── 13. Find Peak Element.cpp │ ├── 14. Custom Sort String.cpp │ ├── 15. Valid Triangle Number.cpp │ ├── 16. 4Sum.cpp │ ├── 18. Reverse Nodes in k-Group.cpp │ ├── 19. Lowest Common Ancestor of a Binary Search Tree.cpp │ ├── 20. Shuffle an Array.cpp │ ├── 21. Push Dominoes.cpp │ ├── 22. Partition Array into Disjoint Intervals.cpp │ ├── 23. Binary Tree Pruning.cpp │ ├── 24. Word Ladder II.cpp │ ├── 26. Convert Sorted Array to Binary Search Tree.cpp │ ├── 27. 3Sum Closest.cpp │ ├── 29. 01 Matrix.cpp │ ├── 30. Map Sum Pairs.cpp │ ├── 31. Trapping Rain Water.cpp │ └── README.md ├── June-2021 │ ├── 01. Max Area of Island.cpp │ ├── 02. Interleaving String.cpp │ ├── 03. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts.cpp │ ├── 04. Open the Lock.cpp │ ├── 05. Maximum Performance of a Team.cpp │ ├── 06. Longest Consecutive Sequence.cpp │ ├── 07. Min Cost Climbing Stairs.cpp │ ├── 08. Construct Binary Tree from Preorder and Inorder Traversal.cpp │ ├── 09. Jump Game VI.cpp │ ├── 10. My Calendar I.cpp │ ├── 11. Stone Game VII.cpp │ ├── 12. Minimum Number of Refueling Stops.cpp │ ├── 13. Palindrome Pairs.cpp │ ├── 14. Maximum Units on a Truck.cpp │ ├── 15. Matchsticks to Square.cpp │ ├── 16. Generate Parentheses.cpp │ ├── 17. Number of Subarrays with Bounded Maximum.cpp │ ├── 18. Range Sum Query - Mutable.cpp │ ├── 19. K Inverse Pairs Array.cpp │ ├── 20. Swim in Rising Water.cpp │ ├── 21. Pascal's Triangle.cpp │ ├── 22. Number of Matching Subsequences.cpp │ ├── 23. Reverse Linked List II.cpp │ ├── 24. Out of Boundary Paths.cpp │ ├── 25. Redundant Connection.cpp │ ├── 26. Count of Smaller Numbers After Self.cpp │ ├── 27. Candy.cpp │ ├── 28. Remove All Adjacent Duplicates In String.cpp │ ├── 29. Max Consecutive Ones III.cpp │ ├── 30. Lowest Common Ancestor of a Binary Tree.cpp │ └── README.md ├── March-2021 │ ├── 01. Distribute Candies.cpp │ ├── 02. Set Mismatch.cpp │ ├── 03. Missing Number.cpp │ ├── 04. Intersection of Two Linked Lists.cpp │ ├── 05. Average of Levels in Binary Tree.cpp │ ├── 06. Short Encoding of Words.cpp │ ├── 07. Design HashMap.cpp │ ├── 08. Remove Palindromic Subsequences.cpp │ ├── 09. Add One Row to Tree.cpp │ ├── 10. Integer to Roman.cpp │ ├── 11. Coin Change.cpp │ ├── 12. Check If a String Contains All Binary Codes of Size K.cpp │ ├── 13. Binary Trees With Factors.cpp │ ├── 14. Swapping Nodes in a Linked List.cpp │ ├── 15. Encode and Decode TinyURL.cpp │ ├── 16. Best Time to Buy and Sell Stock with Transaction Fee.cpp │ ├── 17. Generate Random Point in a Circle.cpp │ ├── 18. Wiggle Subsequence.cpp │ ├── 19. Keys and Rooms.cpp │ ├── 20. Design Underground System.cpp │ ├── 21. Reordered Power of 2.cpp │ ├── 22. Vowel Spellchecker.cpp │ ├── 23. 3Sum With Multiplicity.cpp │ ├── 24. Advantage Shuffle.cpp │ ├── 25. Pacific Atlantic Water Flow.cpp │ ├── 26. Word Subsets.cpp │ ├── 27. Palindromic Substrings.cpp │ ├── 28. Reconstruct Original Digits from English.cpp │ ├── 29. Flip Binary Tree To Match Preorder Traversal.cpp │ ├── 30. Russian Doll Envelopes.cpp │ ├── 31. Stamping The Sequence.cpp │ └── README.md ├── May-2021 │ ├── 01. Prefix and Suffix Search.cpp │ ├── 02. Course Schedule III.cpp │ ├── 03. Running Sum of 1d Array.cpp │ ├── 04. Non-decreasing Array.cpp │ ├── 05. Jump Game II.cpp │ ├── 06. Convert Sorted List to Binary Search Tree.cpp │ ├── 07. Delete Operation for Two Strings.cpp │ ├── 08. Super Palindromes.cpp │ ├── 09. Construct Target Array With Multiple Sums.cpp │ ├── 10. Count Primes.cpp │ ├── 11. Maximum Points You Can Obtain from Cards.cpp │ ├── 12. Range Sum Query 2D - Immutable.cpp │ ├── 13. Ambiguous Coordinates.cpp │ ├── 14. Flatten Binary Tree to Linked List.cpp │ ├── 15. Valid Number.cpp │ ├── 16. Binary Tree Cameras.cpp │ ├── 17. Longest String Chain.cpp │ ├── 18. Find Duplicate File in System.cpp │ ├── 19. Minimum Moves to Equal Array Elements II.cpp │ ├── 20. Binary Tree Level Order Traversal.cpp │ ├── 21. Find and Replace Pattern.cpp │ ├── 22. N-Queens.cpp │ ├── 24. To Lower Case.cpp │ ├── 25. Evaluate Reverse Polish Notation.cpp │ ├── 26. Partitioning Into Minimum Number Of Deci-Binary Numbers.cpp │ ├── 27. Maximum Product of Word Lengths.cpp │ ├── 28. Maximum Erasure Value.cpp │ ├── 29. N-Queens II.cpp │ ├── 30. Maximum Gap.cpp │ ├── 31. Search Suggestions System.cpp │ └── README.md ├── November-2020 │ ├── 01. Convert Binary Number in a Linked List to Integer.cpp │ ├── 02. Insertion Sort List.cpp │ ├── 03. Consecutive Characters.cpp │ ├── 04. Minimum Height Trees.cpp │ ├── 05. Minimum Cost to Move Chips to The Same Position.cpp │ ├── 06. Find the Smallest Divisor Given a Threshold.cpp │ ├── 07. Add Two Numbers II.cpp │ ├── 08. Binary Tree Tilt.cpp │ ├── 09. Maximum Difference Between Node and Ancestor.cpp │ ├── 10. Flipping an Image.cpp │ ├── 11. Valid Square.cpp │ ├── 12. Permutations II.cpp │ ├── 13. Populating Next Right Pointers in Each Node.cpp │ ├── 14. Poor Pigs.cpp │ ├── 15. Range Sum of BST.cpp │ ├── 16. Longest Mountain in Array.cpp │ ├── 17. Mirror Reflection.cpp │ ├── 18. Merge Intervals.cpp │ ├── 19. Decode String.cpp │ ├── 20. Search in Rotated Sorted Array II.cpp │ ├── 21. Numbers At Most N Given Digit Set.cpp │ ├── 22. Unique Morse Code Words.cpp │ ├── 23. House Robber III.cpp │ ├── 24. Basic Calculator II.cpp │ ├── 25. Smallest Integer Divisible by K.cpp │ ├── 30. The Skyline Problem.cpp │ └── README.md ├── October-2020 │ ├── 01. Number of Recent Calls.cpp │ ├── 02. Combination Sum.cpp │ ├── 02. Combination Sum.java │ ├── 03. K-diff Pairs in an Array.cpp │ ├── 04. Remove Covered Intervals.cpp │ ├── 05. Complement of Base 10 Integer.cpp │ ├── 06. Insert into a Binary Search Tree.cpp │ ├── 07. Rotate List.cpp │ ├── 08. Binary Search.cpp │ ├── 08. Binary Search.java │ ├── 09. Serialize and Deserialize BST.cpp │ ├── 10. Minimum Number of Arrows to Burst Balloons.cpp │ ├── 11. Remove Duplicate Letters.cpp │ ├── 12. Buddy Strings.cpp │ ├── 13. Sort List.cpp │ ├── 14. House Robber II.cpp │ ├── 15. Rotate Array.cpp │ ├── 16. Search a 2D Matrix.cpp │ ├── 17. Repeated DNA Sequences.cpp │ ├── 18. Best Time to Buy and Sell Stock IV.cpp │ ├── 19. Minimum Domino Rotations For Equal Row.cpp │ ├── 20. Clone Graph.cpp │ ├── 21. Asteroid Collision.cpp │ ├── 22. Minimum Depth of Binary Tree.cpp │ ├── 23. 132 Pattern.cpp │ ├── 24. Bag of Tokens.cpp │ ├── 25. Stone Game IV.cpp │ ├── 26. Champagne Tower.cpp │ ├── 27. Linked List Cycle II.cpp │ ├── 28. Summary Ranges.cpp │ ├── 29. Maximize distance to Closest Person.cpp │ ├── 30. Number of Longest Increasing Subsequence.cpp │ ├── 31. Recover Binary Search Tree.cpp │ └── README.md ├── October-2021 │ ├── 1. Longest Common Subsequence.cpp │ ├── 10. Bitwise AND of Numbers Range.cpp │ ├── 11. Diameter of Binary Tree.cpp │ ├── 14. Perfect Squares.cpp │ ├── 15. Best Time to Buy and Sell Stock with Cooldown.cpp │ ├── 16. Best Time to Buy and Sell Stock III.cpp │ ├── 17. Path Sum III.cpp │ ├── 18. Cousins in Binary Tree.cpp │ ├── 2. Dungeon Game.cpp │ ├── 3. Jump Game.cpp │ ├── 4. Island Perimeter.cpp │ ├── 5. Climbing Stairs.cpp │ ├── 6. Duplicates In Array.cpp │ ├── 7. Word Search.cpp │ ├── 8. Implement Trie.cpp │ ├── 9. Word Search II.cpp │ └── README.md ├── README.md └── September-2021 │ ├── 01. Array Nesting.cpp │ ├── 02. Unique Binary Search Trees II.cpp │ ├── 06. Slowest Key.cpp │ ├── 07. Reverse Linked List.cpp │ ├── 08. Shifting Letters.cpp │ ├── 09. Largest Plus Sign.cpp │ ├── 13. Maximum Number of Balloons.cpp │ ├── 14. Reverse Only Letters.cpp │ ├── 15. Longest Turbulent Subarray.cpp │ ├── 16. Spiral Matrix.cpp │ ├── 17. Intersection of Two Arrays II.cpp │ ├── 20. Find Winner on a Tic Tac Toe Game.cpp │ ├── 21. Max Consecutive Ones.cpp │ ├── 22. Maximum Length of a Concatenated String with Unique Characters.cpp │ ├── 23. Break a Palindrome.cpp │ ├── Maximum Average Subtree.cpp │ ├── Minimize Max Distance to Gas Station.cpp │ ├── README.md │ └── Shortest Distance from All Buildings.cpp ├── Leetcode Study Plan └── README.md ├── Leetcode Top Interview Questions ├── README.md └── solutions │ ├── 3Sum.cpp │ ├── 4Sum.cpp │ ├── Add Two Numbers.cpp │ ├── Best Time to Buy and Sell Stock II.cpp │ ├── Best Time to Buy and Sell Stock.cpp │ ├── Binary Tree Inorder Traversal.cpp │ ├── Binary Tree Level Order Traversal.cpp │ ├── Binary Tree Zigzag Level Order Traversal.cpp │ ├── Climbing Stairs.cpp │ ├── Coin Change.cpp │ ├── Construct Binary Tree from Preorder and Inorder Traversal.cpp │ ├── Contains Duplicate.cpp │ ├── Convert Sorted Array to Binary Search Tree.cpp │ ├── Count Primes.cpp │ ├── Delete Node in a Linked List.cpp │ ├── Divide Two Integers.cpp │ ├── Evaluate Reverse Polish Notation.cpp │ ├── Excel Sheet Column Number.cpp │ ├── Find First and Last Position of Element in Sorted Array.cpp │ ├── Find Peak Element.cpp │ ├── First Bad Version.cpp │ ├── First Missing Positive.cpp │ ├── First Unique Character in a String.cpp │ ├── Fizz Buzz.cpp │ ├── Fraction to Recurring Decimal.cpp │ ├── Generate Parentheses.cpp │ ├── Group Anagrams.cpp │ ├── Group The People Given By Group Size.cpp │ ├── Hamming Distance.cpp │ ├── Happy Number.cpp │ ├── House Robber.cpp │ ├── Implement strStr.cpp │ ├── Insert Delete GetRandom O(1).cpp │ ├── Intersection of Two Arrays II.cpp │ ├── Intersection of Two Linked Lists.cpp │ ├── Jump Game.cpp │ ├── Kth Largest Element in an Array.cpp │ ├── Kth Missing Positive Number.cpp │ ├── Kth Smallest Element in a BST.cpp │ ├── Letter Combinations of a Phone Number.cpp │ ├── Linked List Cycle II.cpp │ ├── Linked List Cycle.cpp │ ├── Longest Common Prefix.cpp │ ├── Longest Common Subsequence.cpp │ ├── Longest Increasing Subsequence.cpp │ ├── Longest Palindromic Substring.cpp │ ├── Longest Substring Without Repeating Characters.cpp │ ├── Majority Element II.cpp │ ├── Majority Element.cpp │ ├── Max Increase To Keep City Skyline.cpp │ ├── Maximum Depth of Binary Tree.cpp │ ├── Maximum Subarray.cpp │ ├── Merge Intervals.cpp │ ├── Merge Sorted Array.cpp │ ├── Merge Two Sorted Lists.cpp │ ├── Min Stack.cpp │ ├── Minimum Number Of Operations To Move All Balls To Each Box.cpp │ ├── Minimum Number of Days to Eat N Oranges.cpp │ ├── Minimum numberof vertices.cpp │ ├── Missing Number.cpp │ ├── Move Zeroes.cpp │ ├── Next Permutation.cpp │ ├── Number of 1 Bits.cpp │ ├── Number of Islands.cpp │ ├── Odd Even Linked List.cpp │ ├── Palindrome Linked List.cpp │ ├── Pascals Triangle.cpp │ ├── Permutations II.cpp │ ├── Permutations.cpp │ ├── Plus One.cpp │ ├── Populating Next Right Pointers in Each Node.cpp │ ├── Pow(x, n).cpp │ ├── Power of Four.cpp │ ├── Power of Three.cpp │ ├── Product of Array Except Self.cpp │ ├── Remove Duplicates from Sorted Array.cpp │ ├── Remove Nth Node From End of List.cpp │ ├── Repeated DNA Sequences.cpp │ ├── Reverse Bits.cpp │ ├── Reverse Linked List.cpp │ ├── Reverse String.cpp │ ├── Roman to Integer.cpp │ ├── Rotate Array.cpp │ ├── Rotate Image.cpp │ ├── Search a 2D Matrix II.cpp │ ├── Search for a Range.cpp │ ├── Serialize and Deserialize Binary Tree.cpp │ ├── Set Matrix Zeroes.cpp │ ├── Shuffle an Array.cpp │ ├── Single Number.cpp │ ├── Sliding Window Maximum.cpp │ ├── Sort Colors.cpp │ ├── Sqrt(x).cpp │ ├── String to Integer (atoi).cpp │ ├── Subrectangle%20Queries.cpp │ ├── Subsets.cpp │ ├── Sum of Two Integers.cpp │ ├── Summary Ranges.cpp │ ├── Super Egg Drop.cpp │ ├── Symmetric Tree.cpp │ ├── Task Scheduler.cpp │ ├── Top K Frequent Elements.cpp │ ├── Trapping Rain Water.cpp │ ├── Two Sum.cpp │ ├── Unique Paths.cpp │ ├── Valid Anagram.cpp │ ├── Valid Palindrome.cpp │ ├── Valid Parentheses.cpp │ ├── Valid Sudoku.cpp │ ├── Validate Binary Search Tree.cpp │ ├── Word Break.cpp │ ├── Word Search.cpp │ └── Zig Zag Conversion.cpp ├── README.md ├── Resources ├── Articles │ ├── CPP-STL.md │ ├── CPP-SYNTAX.md │ └── GitCheatsheet.md └── images │ ├── Complexity Chart.png │ ├── Data Structures.png │ └── STL Table.png ├── Striver Sheet ├── Day-1 │ ├── Find Missing And Repeating.cpp │ ├── Find the Duplicate Number.cpp │ ├── Maximum Subarray.cpp │ ├── Merge Intervals.cpp │ ├── Merge Two Sorted Arrays.cpp │ └── Sort Colors.cpp ├── Day-10 │ ├── N-Queens.cpp │ ├── Permutations.cpp │ ├── Rat in a Maze Problem.cpp │ ├── Sudoku Solver.cpp │ └── Word Break.cpp ├── Day-11 │ ├── Median in a row-wise sorted Matrix.cpp │ ├── Median of Two Sorted Arrays.cpp │ ├── Search in Rotated Sorted Array.cpp │ └── Single Element in a Sorted Array.cpp ├── Day-12 │ ├── Counting Bits.cpp │ ├── Find MSB In O1.cpp │ ├── Power of Two.cpp │ └── Subsets.cpp ├── Day-13 │ ├── BFS of graph.cpp │ ├── Implement Queue using Linked List.cpp │ ├── Implement Queue using Stacks.cpp │ ├── Implement Queue using array.cpp │ ├── Implement Stack using Linked List.cpp │ ├── Implement Stack using Queues.cpp │ ├── Implement stack using array.cpp │ ├── Next Greater Element.cpp │ └── Valid Parentheses.cpp ├── Day-14 │ ├── LRU Cache.cpp │ ├── Largest Rectangle in Histogram.cpp │ ├── Min Stack.cpp │ ├── Nearest Smaller Element.cpp │ ├── Rotting Oranges.cpp │ └── Sliding Window Maximum.cpp ├── Day-15 │ ├── Implement strStr.cpp │ ├── Integer to Roman.cpp │ ├── Longest Common Prefix.cpp │ ├── Longest Palindromic Substring.cpp │ ├── Reverse Words in a String.cpp │ ├── Roman to Integer.cpp │ └── String to Integer.cpp ├── Day-16 │ ├── Compare Version Numbers.cpp │ ├── Count and Say.cpp │ └── Valid Anagram.cpp ├── Day-17 │ ├── Binary Tree Inorder Traversal.cpp │ ├── Binary Tree Postorder Traversal.cpp │ ├── Binary Tree Preorder Traversal.cpp │ ├── Binary Tree Right Side View.cpp │ ├── Bottom View of Binary Tree.cpp │ └── Top View of Binary Tree.cpp ├── Day-18 │ ├── Balanced Binary Tree.cpp │ ├── Binary Tree Level Order Traversal.cpp │ ├── Binary Tree Zigzag Level Order Traversal.cpp │ ├── Diameter of Binary Tree.cpp │ ├── Lowest Common Ancestor of a Binary Tree.cpp │ ├── Maximum Depth of Binary Tree.cpp │ └── Same Tree.cpp ├── Day-19 │ ├── Binary Tree Maximum Path Sum.cpp │ ├── Construct Binary Tree from Inorder and Postorder Traversal.cpp │ ├── Construct Binary Tree from Preorder and Inorder Traversal.cpp │ ├── Flatten Binary Tree to Linked List.cpp │ └── Symmetric Tree.cpp ├── Day-2 │ ├── Best Time to Buy and Sell Stock.cpp │ ├── Count Inversions.cpp │ ├── Next Permutation.cpp │ ├── Pascal's Triangle.cpp │ ├── Rotate Image.cpp │ └── Set Matrix Zeroes.cpp ├── Day-20 │ ├── Convert Sorted Array to Binary Search Tree.cpp │ ├── Lowest Common Ancestor of a BST.cpp │ ├── Populating Next Right Pointers in Each Node.cpp │ ├── Predecessor and Successor.cpp │ ├── Search in a Binary Search Tree.cpp │ └── Validate Binary Search Tree.cpp ├── Day-21 │ ├── Binary Search Tree Iterator.cpp │ ├── Kth Smallest Element in a BST.cpp │ ├── Kth largest element in BST.cpp │ ├── Largest BST.cpp │ ├── Serialize and Deserialize Binary Tree.cpp │ └── Two Sum IV - Input is a BST.cpp ├── Day-22 │ ├── Binary Tree to DLL.cpp │ ├── Distinct Numbers in Window.cpp │ ├── Find Median from Data Stream.cpp │ ├── Flood Fill.cpp │ ├── Kth Largest Element in a Stream.cpp │ └── Kth Largest Element in an Array.cpp ├── Day-23 │ ├── BFS of graph.cpp │ ├── Clone Graph.cpp │ ├── DFS of Graph.cpp │ ├── Detect cycle in a directed graph.cpp │ ├── Detect cycle in an undirected graph.cpp │ ├── Is Graph Bipartite.cpp │ ├── Number of Islands.cpp │ └── Topological sort.cpp ├── Day-3 │ ├── Majority Element II.cpp │ ├── Majority Element.cpp │ ├── Powxn.cpp │ ├── Reverse Pairs.cpp │ ├── Search a 2D Matrix.cpp │ └── Unique Paths.cpp ├── Day-4 │ ├── 4Sum.cpp │ ├── Largest subarray with 0 sum.cpp │ ├── Longest Consecutive Sequence.cpp │ ├── Longest Substring Without Repeating Characters.cpp │ └── Two Sum.cpp ├── Day-5 │ ├── Add Two Numbers.cpp │ ├── Delete Node in a Linked List.cpp │ ├── Merge Two Sorted Lists.cpp │ ├── Middle of the Linked List.cpp │ ├── Remove Nth Node From End of List.cpp │ └── Reverse Linked List.cpp ├── Day-6 │ ├── Flattening a Linked List.cpp │ ├── Intersection of Two Linked Lists.cpp │ ├── Linked List Cycle II.cpp │ ├── Linked List Cycle.cpp │ ├── Palindrome Linked List.cpp │ ├── Reverse Nodes in k-Group.cpp │ └── Rotate List.cpp ├── Day-7 │ ├── 3Sum.cpp │ ├── Copy List with Random Pointer.cpp │ ├── Max Consecutive Ones.cpp │ ├── Remove Duplicates.cpp │ └── Trapping Rain Water.cpp ├── Day-8 │ ├── Fractional Knapsack.cpp │ ├── Job Sequencing Problem.cpp │ ├── Minimum Platforms.cpp │ └── N meetings in one room.cpp ├── Day-9 │ ├── Combination Sum II.cpp │ ├── Combination Sum.cpp │ ├── Palindrome Partitioning.cpp │ ├── Permutation Sequence.cpp │ ├── Subset Sums.cpp │ └── Subsets II.cpp └── README.md └── _config.yml /.editorconfig: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sachuverma/DataStructures-Algorithms/c5dddef53cb1784fbeabd913c2affbf7a36b4ea8/.editorconfig -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.associations": { 3 | "array": "cpp", 4 | "bitset": "cpp", 5 | "string_view": "cpp", 6 | "initializer_list": "cpp", 7 | "regex": "cpp", 8 | "utility": "cpp", 9 | "valarray": "cpp", 10 | "chrono": "cpp", 11 | "random": "cpp", 12 | "limits": "cpp", 13 | "deque": "cpp", 14 | "forward_list": "cpp", 15 | "list": "cpp", 16 | "string": "cpp", 17 | "unordered_map": "cpp", 18 | "unordered_set": "cpp", 19 | "vector": "cpp", 20 | "complex": "cpp", 21 | "iostream": "cpp", 22 | "cmath": "cpp", 23 | "*.tcc": "cpp", 24 | "any": "cpp", 25 | "type_traits": "cpp" 26 | } 27 | } -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/Check If Circular Linked List.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Check If Circular Linked List 3 | ============================= 4 | 5 | Given a singly linked list, find if the linked list is circular or not. A linked list is called circular if it not NULL terminated and all nodes are connected in the form of a cycle. An empty linked list is considered as circular. 6 | 7 | Example 1: 8 | Input: 9 | LinkedList: 1->2->3->4->5 10 | (the first and last node is connected, 11 | i.e. 5 --> 1) 12 | Output: 1 13 | 14 | Example 2: 15 | Input: 16 | LinkedList: 2->4->6->7->5->1 17 | Output: 0 18 | Your Task: 19 | The task is to complete the function isCircular() which checks if the given linked list is circular or not. It should return true or false accordingly. (the driver code prints 1 if the returned values is true, otherwise 0) 20 | 21 | Expected Time Complexity: O(N). 22 | Expected Auxiliary Space: O(1). 23 | 24 | Constraints: 25 | 1 <=Number of nodes<= 100 26 | */ 27 | 28 | bool isCircular(Node *head) 29 | { 30 | auto temp = head; 31 | while (temp) 32 | { 33 | temp = temp->next; 34 | if (temp == head) 35 | return true; 36 | } 37 | return false; 38 | } 39 | -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/Convert BST to Min Heap.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sachuverma/DataStructures-Algorithms/c5dddef53cb1784fbeabd913c2affbf7a36b4ea8/DSA Crack Sheet/solutions/Convert BST to Min Heap.cpp -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/Count Squares.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Count Squares 3 | ============= 4 | 5 | Consider a sample space S consisting of all perfect squares starting from 1, 4, 9 and so on. You are given a number N, you have to output the number of integers less than N in the sample space S. 6 | 7 | Example 1: 8 | Input : 9 | N = 9 10 | Output: 11 | 2 12 | Explanation: 13 | 1 and 4 are the only Perfect Squares 14 | less than 9. So, the Output is 2. 15 | 16 | Example 2: 17 | Input : 18 | N = 3 19 | Output: 20 | 1 21 | Explanation: 22 | 1 is the only Perfect Square 23 | less than 3. So, the Output is 1. 24 | 25 | Your Task: 26 | You don't need to read input or print anything. Your task is to complete the function countSquares() which takes an Integer N as input and returns the answer. 27 | 28 | Expected Time Complexity: O(sqrt(N)) 29 | Expected Auxiliary Space: O(1) 30 | */ 31 | 32 | int countSquares(int N) 33 | { 34 | int n = ceil(sqrt(N)); 35 | return n - 1; 36 | } 37 | -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/Count pairs with given sum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Count pairs with given sum 3 | ========================== 4 | 5 | Given an array of N integers, and an integer K, find the number of pairs of elements in the array whose sum is equal to K. 6 | 7 | Example 1: 8 | Input: 9 | N = 4, K = 6 10 | arr[] = {1, 5, 7, 1} 11 | Output: 2 12 | Explanation: 13 | arr[0] + arr[1] = 1 + 5 = 6 14 | and arr[1] + arr[3] = 5 + 1 = 6. 15 | 16 | Example 2: 17 | Input: 18 | N = 4, X = 2 19 | arr[] = {1, 1, 1, 1} 20 | Output: 6 21 | Explanation: 22 | Each 1 will produce sum 2 with any 1. 23 | Your Task: 24 | You don't need to read input or print anything. Your task is to complete the function getPairsCount() which takes arr[], n and k as input parameters and returns the number of pairs that have sum K. 25 | 26 | Expected Time Complexity: O(N) 27 | Expected Auxiliary Space: O(N) 28 | 29 | Constraints: 30 | 1 <= N <= 105 31 | 1 <= K <= 108 32 | 1 <= Arr[i] <= 106 33 | */ 34 | 35 | int getPairsCount(int arr[], int n, int k) 36 | { 37 | unordered_map freq; 38 | for (int i = 0; i < n; ++i) 39 | freq[arr[i]]++; 40 | int ans = 0; 41 | for (int i = 0; i < n; ++i) 42 | { 43 | ans += freq[k - arr[i]]; 44 | if (k == 2 * arr[i]) 45 | ans--; 46 | } 47 | return ans / 2; 48 | } 49 | -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/Cyclically rotate an array by one.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Cyclically rotate an array by one 3 | ================================= 4 | 5 | Given an array, rotate the array by one position in clock-wise direction. 6 | 7 | Example 1: 8 | Input: 9 | N = 5 10 | A[] = {1, 2, 3, 4, 5} 11 | Output: 12 | 5 1 2 3 4 13 | 14 | Example 2: 15 | Input: 16 | N = 8 17 | A[] = {9, 8, 7, 6, 4, 2, 1, 3} 18 | Output: 19 | 3 9 8 7 6 4 2 1 20 | 21 | Your Task: 22 | You don't need to read input or print anything. Your task is to complete the function rotate() which takes the array A[] and its size N as inputs and modify the array. 23 | 24 | Expected Time Complexity: O(N) 25 | Expected Auxiliary Space: O(1) 26 | 27 | Constraints: 28 | 1<=N<=105 29 | 0<=a[i]<=105 30 | */ 31 | 32 | //User function Template for C++ 33 | 34 | void rotate(int arr[], int n) 35 | { 36 | int elem = arr[n - 1]; 37 | for (auto i = n; i >= 1; --i) 38 | { 39 | arr[i] = arr[i - 1]; 40 | } 41 | arr[0] = elem; 42 | } 43 | -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/Detect Loop in linked list.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Detect Loop in linked list 3 | ========================== 4 | 5 | Given a linked list of N nodes. The task is to check if the linked list has a loop. Linked list can contain self loop. 6 | 7 | Example 1: 8 | Input: 9 | N = 3 10 | value[] = {1,3,4} 11 | x = 2 12 | Output: True 13 | Explanation: In above test case N = 3. 14 | The linked list with nodes N = 3 is 15 | given. Then value of x=2 is given which 16 | means last node is connected with xth 17 | node of linked list. Therefore, there 18 | exists a loop. 19 | 20 | Example 2: 21 | Input: 22 | N = 4 23 | value[] = {1,8,3,4} 24 | x = 0 25 | Output: False 26 | Explanation: For N = 4 ,x = 0 means 27 | then lastNode->next = NULL, then 28 | the Linked list does not contains 29 | any loop. 30 | Your Task: 31 | The task is to complete the function detectloop() which contains reference to the head as only argument. This function should return 1 if linked list contains loop, else return 0. 32 | 33 | Expected Time Complexity: O(N) 34 | Expected Auxiliary Space: O(1) 35 | 36 | Constraints: 37 | 1 <= N <= 104 38 | 1 <= Data on Node <= 103 39 | */ 40 | 41 | bool detectLoop(Node *head) 42 | { 43 | Node *fast = head, *slow = head; 44 | while (fast && fast->next) 45 | { 46 | fast = fast->next->next; 47 | slow = slow->next; 48 | if (fast == slow) 49 | return true; 50 | } 51 | return false; 52 | } 53 | -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/Diameter of Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Diameter of Binary Tree 3 | ======================= 4 | 5 | Given a Binary Tree, find diameter of it. 6 | The diameter of a tree is the number of nodes on the longest path between two end nodes in the tree. The diagram below shows two trees each with diameter nine, the leaves that form the ends of a longest path are shaded (note that there is more than one path in each tree of length nine, but no path longer than nine nodes). 7 | 8 | Example 1: 9 | Input: 10 | 1 11 | / \ 12 | 2 3 13 | Output: 3 14 | 15 | Example 2: 16 | Input: 17 | 10 18 | / \ 19 | 20 30 20 | / \ 21 | 40 60 22 | Output: 4 23 | Your Task: 24 | You need to complete the function diameter() that takes root as parameter and returns the diameter. 25 | 26 | Expected Time Complexity: O(N). 27 | Expected Auxiliary Space: O(Height of the Tree). 28 | 29 | Constraints: 30 | 1 <= Number of nodes <= 10000 31 | 1 <= Data of a node <= 1000 32 | */ 33 | 34 | int ans = 0; 35 | 36 | int helper(Node *root) 37 | { 38 | if (!root) 39 | return 0; 40 | int left = helper(root->left); 41 | int right = helper(root->right); 42 | ans = max(ans, 1 + left + right); 43 | return max(left, right) + 1; 44 | } 45 | 46 | int diameter(Node *root) 47 | { 48 | helper(root); 49 | return ans; 50 | } -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/Equivalent numeric keypad sequence.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Equivalent numeric keypad sequence 3 | =================================== 4 | 5 | Given a sentence in the form of a string, convert it into its equivalent mobile numeric keypad sequence. 6 | 7 | Examples : 8 | Input : GEEKSFORGEEKS 9 | Output : 4333355777733366677743333557777 10 | For obtaining a number, we need to press a 11 | number corresponding to that character for 12 | number of times equal to position of the 13 | character. For example, for character C, 14 | we press number 2 three times and accordingly. 15 | 16 | Input : HELLO WORLD 17 | Output : 4433555555666096667775553 18 | */ 19 | 20 | #include 21 | using namespace std; 22 | 23 | int main() 24 | { 25 | string codes[] = {"2", "22", "222", "3", "33", "333", "4", "44", "444", "5", "55", "555", "6", "66", "666", "7", "77", "777", "7777", "8", "88", "888", "9", "99", "999", "9999"}; 26 | 27 | string input = "A B C EJI"; 28 | string ans = ""; 29 | 30 | for (auto &i : input) 31 | { 32 | if (i == ' ') 33 | ans += '0'; 34 | else 35 | ans += codes[i - 'A']; 36 | } 37 | cout << ans; 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/Factorials of large numbers.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Factorials of large numbers 3 | =========================== 4 | 5 | Given an integer, the task is to find factorial of the number. 6 | 7 | Input: 8 | The first line of input contains an integer T denoting the number of test cases. 9 | The first line of each test case is N,the number whose factorial is to be found 10 | 11 | Output: 12 | Print the factorial of the number in separate line. 13 | 14 | Constraints: 15 | 1 ≤ T ≤ 100 16 | 1 ≤ N ≤ 1000 17 | 18 | Example: 19 | Input: 20 | 3 21 | 5 22 | 10 23 | 2 24 | 25 | Output: 26 | 120 27 | 3628800 28 | 2 29 | */ 30 | 31 | #include 32 | using namespace std; 33 | 34 | int main() 35 | { 36 | int t; 37 | cin >> t; 38 | while (t--) 39 | { 40 | int n; 41 | cin >> n; 42 | string ans = "1"; 43 | for (int i = 2; i <= n; ++i) 44 | { 45 | int carry = 0; 46 | for (auto &ch : ans) 47 | { 48 | int num = ch - '0'; 49 | num = i * num; 50 | num += carry; 51 | int digit = num % 10; 52 | ch = (digit + '0'); 53 | carry = num / 10; 54 | } 55 | 56 | while (carry) 57 | { 58 | int digit = carry % 10; 59 | carry = carry / 10; 60 | ans += to_string(digit); 61 | } 62 | } 63 | 64 | reverse(ans.begin(), ans.end()); 65 | cout << ans << endl; 66 | } 67 | return 0; 68 | } 69 | -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/Find Missing And Repeating.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Find Missing And Repeating 3 | ========================== 4 | 5 | Given an unsorted array Arr of size N of positive integers. One number 'A' from set {1, 2, …N} is missing and one number 'B' occurs twice in array. Find these two numbers. 6 | 7 | Example 1: 8 | Input: 9 | N = 2 10 | Arr[] = {2, 2} 11 | Output: 2 1 12 | Explanation: Repeating number is 2 and 13 | smallest positive missing number is 1. 14 | 15 | Example 2: 16 | Input: 17 | N = 3 18 | Arr[] = {1, 3, 3} 19 | Output: 3 2 20 | Explanation: Repeating number is 3 and 21 | smallest positive missing number is 2. 22 | Your Task: 23 | You don't need to read input or print anything. Your task is to complete the function findTwoElement() which takes the array of integers arr and n as parameters and returns an array of integers of size 2 denoting the answer ( The first index contains B and second index contains A.) 24 | 25 | Expected Time Complexity: O(N) 26 | Expected Auxiliary Space: O(1) 27 | 28 | Constraints: 29 | 1 ≤ N ≤ 105 30 | 1 ≤ Arr[i] ≤ N 31 | */ 32 | 33 | int *findTwoElement(int *arr, int n) 34 | { 35 | int *ans = new int[2]; 36 | for (int i = 0; i < n; i++) 37 | if (arr[abs(arr[i]) - 1] > 0) 38 | arr[abs(arr[i]) - 1] *= -1; 39 | else 40 | ans[0] = abs(arr[i]); 41 | 42 | for (int i = 0; i < n; i++) 43 | if (arr[i] > 0) 44 | ans[1] = i + 1; 45 | return ans; 46 | } 47 | -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/Find the Duplicate Number.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Find the Duplicate Number 3 | ========================= 4 | 5 | Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive. 6 | 7 | There is only one repeated number in nums, return this repeated number. 8 | 9 | Example 1: 10 | Input: nums = [1,3,4,2,2] 11 | Output: 2 12 | 13 | Example 2: 14 | Input: nums = [3,1,3,4,2] 15 | Output: 3 16 | 17 | Example 3: 18 | Input: nums = [1,1] 19 | Output: 1 20 | 21 | Example 4: 22 | Input: nums = [1,1,2] 23 | Output: 1 24 | 25 | 26 | Constraints: 27 | 2 <= n <= 3 * 104 28 | nums.length == n + 1 29 | 1 <= nums[i] <= n 30 | All the integers in nums appear only once except for precisely one integer which appears two or more times. 31 | 32 | Follow up: 33 | How can we prove that at least one duplicate number must exist in nums? 34 | Can you solve the problem without modifying the array nums? 35 | Can you solve the problem using only constant, O(1) extra space? 36 | Can you solve the problem with runtime complexity less than O(n2)? 37 | */ 38 | 39 | class Solution 40 | { 41 | public: 42 | int findDuplicate(vector &nums) 43 | { 44 | for (int i = 0; i < nums.size(); ++i) 45 | { 46 | int index = abs(nums[i]) - 1; 47 | if (nums[index] < 0) 48 | return index + 1; 49 | else 50 | nums[index] = -nums[index]; 51 | } 52 | return 0; 53 | } 54 | }; 55 | -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/Height of Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Height of Binary Tree 3 | ====================== 4 | 5 | Given a binary tree, find its height. 6 | 7 | Example 1: 8 | Input: 9 | 1 10 | / \ 11 | 2 3 12 | Output: 2 13 | 14 | Example 2: 15 | Input: 16 | 2 17 | \ 18 | 1 19 | / 20 | 3 21 | Output: 3 22 | 23 | Your Task: 24 | You don't need to read input or print anything. Your task is to complete the function height() which takes root node of the tree as input parameter and returns an integer denoting the height of the tree. If the tree is empty, return 0. 25 | 26 | Expected Time Complexity: O(N) 27 | Expected Auxiliary Space: O(N) 28 | 29 | Constraints: 30 | 1 <= Number of nodes <= 105 31 | 1 <= Data of a node <= 105 32 | */ 33 | 34 | class Solution 35 | { 36 | public: 37 | int height(struct Node *node) 38 | { 39 | if (!node) 40 | return 0; 41 | return 1 + max(height(node->left), height(node->right)); 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/Kadane's Algorithm.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Kadane's Algorithm 3 | ================== 4 | 5 | Given an array arr of N integers. Find the contiguous sub-array with maximum sum. 6 | 7 | Example 1: 8 | Input: 9 | N = 5 10 | arr[] = {1,2,3,-2,5} 11 | Output: 12 | 9 13 | Explanation: 14 | Max subarray sum is 9 15 | of elements (1, 2, 3, -2, 5) which 16 | is a contiguous subarray. 17 | 18 | Example 2: 19 | Input: 20 | N = 4 21 | arr[] = {-1,-2,-3,-4} 22 | Output: 23 | -1 24 | Explanation: 25 | Max subarray sum is -1 26 | of element (-1) 27 | 28 | Your Task: 29 | You don't need to read input or print anything. The task is to complete the function maxSubarraySum() which takes arr and N as input parameters and returns the sum of subarray with maximum sum. 30 | 31 | Expected Time Complexity: O(N) 32 | Expected Auxiliary Space: O(1) 33 | 34 | Constraints: 35 | 1 ≤ N ≤ 106 36 | -107 ≤ A[i] <= 107 37 | */ 38 | 39 | // Function to find subarray with maximum sum 40 | // arr: input array 41 | // n: size of array 42 | 43 | int maxSubarraySum(int arr[], int n) 44 | { 45 | int max_sum = 0, curr_sum = 0; 46 | for (int i = 0; i < n; ++i) 47 | { 48 | curr_sum += arr[i]; 49 | max_sum = max(max_sum, curr_sum); 50 | if (curr_sum < 0) 51 | curr_sum = 0; 52 | } 53 | 54 | return max_sum; 55 | } 56 | -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/Kth largest element in BST.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Kth largest element in BST 3 | ========================== 4 | 5 | Given a Binary search tree. Your task is to complete the function which will return the Kth largest element without doing any modification in Binary Search Tree. 6 | 7 | Example 1: 8 | Input: 9 | 4 10 | / \ 11 | 2 9 12 | k = 2 13 | Output: 4 14 | 15 | Example 2: 16 | Input: 17 | 9 18 | \ 19 | 10 20 | K = 1 21 | Output: 10 22 | 23 | Your Task: 24 | You don't need to read input or print anything. Your task is to complete the function kthLargest() which takes the root of the BST and an integer K as inputs and returns the Kth largest element in the given BST. 25 | 26 | Expected Time Complexity: O(H + K). 27 | Expected Auxiliary Space: O(H) 28 | 29 | Constraints: 30 | 1 <= N <= 1000 31 | 1 <= K <= N 32 | */ 33 | 34 | class Solution 35 | { 36 | public: 37 | int ans = INT_MIN; 38 | void inorder(Node *root, int &k) 39 | { 40 | if (k == 0 || !root) 41 | return; 42 | inorder(root->right, k); 43 | k--; 44 | if (k == 0) 45 | ans = root->data; 46 | inorder(root->left, k); 47 | } 48 | 49 | int kthLargest(Node *root, int K) 50 | { 51 | inorder(root, K); 52 | return ans; 53 | } 54 | }; -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/Kth smallest element.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Kth smallest element 3 | ==================== 4 | 5 | Given an array arr[] and a number K where K is smaller than size of array, the task is to find the Kth smallest element in the given array. It is given that all array elements are distinct. 6 | 7 | Example 1: 8 | Input: 9 | N = 6 10 | arr[] = 7 10 4 3 20 15 11 | K = 3 12 | Output : 7 13 | Explanation : 14 | 3rd smallest element in the given 15 | array is 7. 16 | 17 | Example 2: 18 | Input: 19 | N = 5 20 | arr[] = 7 10 4 20 15 21 | K = 4 22 | Output : 15 23 | Explanation : 24 | 4th smallest element in the given 25 | array is 15. 26 | Your Task: 27 | You don't have to read input or print anything. Your task is to complete the function kthSmallest() which takes the array, it's size and an integer k as input and returns the kth smallest element. 28 | 29 | 30 | Expected Time Complexity: O(n) 31 | Expected Auxiliary Space: O(1) 32 | 33 | Constraints: 34 | 1 <= N <= 105 35 | 1 <= arr[i] <= 105 36 | 1 <= K <= N 37 | */ 38 | 39 | // arr : given array 40 | // l : starting index of the array i.e 0 41 | // r : ending index of the array i.e size-1 42 | // k : find kth smallest element and return using this function 43 | 44 | int kthSmallest(int arr[], int l, int r, int k) 45 | { 46 | sort(arr + l, arr + r + 1); 47 | return arr[k - 1]; 48 | } -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/Level order traversal.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Level order traversal 3 | ===================== 4 | 5 | Given a binary tree, find its level order traversal. 6 | Level order traversal of a tree is breadth-first traversal for the tree. 7 | 8 | Example 1: 9 | Input: 10 | 1 11 | / \ 12 | 3 2 13 | Output:1 3 2 14 | 15 | Example 2: 16 | Input: 17 | 10 18 | / \ 19 | 20 30 20 | / \ 21 | 40 60 22 | Output:10 20 30 40 60 N N 23 | 24 | Your Task: 25 | You don't have to take any input. Complete the function levelOrder() that takes the root node as input parameter and returns a list of integers containing the level order traversal of the given Binary Tree. 26 | 27 | Expected Time Complexity: O(N) 28 | Expected Auxiliary Space: O(N) 29 | 30 | Constraints: 31 | 1 ≤ Number of nodes ≤ 105 32 | 1 ≤ Data of a node ≤ 105 33 | */ 34 | 35 | vector levelOrder(Node *node) 36 | { 37 | vector ans; 38 | queue q; 39 | q.push(node); 40 | while (q.size()) 41 | { 42 | auto curr = q.front(); 43 | q.pop(); 44 | ans.push_back(curr->data); 45 | if (curr->left) 46 | q.push(curr->left); 47 | if (curr->right) 48 | q.push(curr->right); 49 | } 50 | return ans; 51 | } 52 | -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/Longest Common Prefix.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Longest Common Prefix 3 | ===================== 4 | 5 | Write a function to find the longest common prefix string amongst an array of strings. 6 | 7 | If there is no common prefix, return an empty string "". 8 | 9 | Example 1: 10 | Input: strs = ["flower","flow","flight"] 11 | Output: "fl" 12 | 13 | Example 2: 14 | Input: strs = ["dog","racecar","car"] 15 | Output: "" 16 | Explanation: There is no common prefix among the input strings. 17 | 18 | Constraints: 19 | 0 <= strs.length <= 200 20 | 0 <= strs[i].length <= 200 21 | strs[i] consists of only lower-case English letters. 22 | */ 23 | 24 | class Solution 25 | { 26 | public: 27 | string longestCommonPrefix(vector &strs) 28 | { 29 | if (!strs.size()) 30 | return ""; 31 | string ans = strs[0]; 32 | 33 | for (auto &word : strs) 34 | { 35 | int i = 0, j = 0, flag = 1; 36 | 37 | while (i < ans.size() && j < word.size()) 38 | { 39 | if (ans[i] == word[j]) 40 | { 41 | i++; 42 | j++; 43 | } 44 | else 45 | { 46 | flag++; 47 | break; 48 | } 49 | } 50 | 51 | if (!flag && i == 0) 52 | return ""; 53 | ans = ans.substr(0, i); 54 | } 55 | 56 | return ans; 57 | } 58 | }; 59 | -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/Longest Prefix Suffix.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Longest Prefix Suffix 3 | ===================== 4 | 5 | Given a string of characters, find the length of the longest proper prefix which is also a proper suffix. 6 | 7 | Example 1: 8 | Input: s = "abab" 9 | Output: 2 10 | Explanation: "ab" is the longest proper 11 | prefix and suffix. 12 | 13 | Example 2: 14 | Input: s = "aaaa" 15 | Output: 3 16 | Explanation: "aaa" is the longest proper 17 | prefix and suffix. 18 | Your task: 19 | You do not need to read any input or print anything. The task is to complete the function lps(), which takes a string as input and returns an integer. 20 | 21 | Expected Time Complexity: O(|str|) 22 | Expected Auxiliary Space: O(|str|) 23 | 24 | Constraints: 25 | 1 ≤ |s| ≤ 105 26 | s contains lower case English alphabets 27 | */ 28 | 29 | int lps(string s) 30 | { 31 | int n = s.size(), len = 0; 32 | vector lps(n, 0); 33 | lps[0] = 0; 34 | 35 | int i = 1; 36 | while (i < n) 37 | { 38 | if (s[i] == s[len]) 39 | { 40 | len++; 41 | lps[i] = len; 42 | i++; 43 | } 44 | else 45 | { 46 | if (len != 0) 47 | len = lps[len - 1]; 48 | else 49 | { 50 | lps[i] = 0; 51 | i++; 52 | } 53 | } 54 | } 55 | return lps[n - 1]; 56 | } 57 | -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/Lowest Common Ancestor in a BST.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Lowest Common Ancestor in a BST 3 | =============================== 4 | 5 | Given a Binary Search Tree (with all values unique) and two node values. Find the Lowest Common Ancestors of the two nodes in the BST. 6 | 7 | Example 1: 8 | Input: 9 | 5 10 | / \ 11 | 4 6 12 | / \ 13 | 3 7 14 | \ 15 | 8 16 | n1 = 7, n2 = 8 17 | Output: 7 18 | 19 | Example 2: 20 | Input: 21 | 2 22 | / \ 23 | 1 3 24 | n1 = 1, n2 = 3 25 | Output: 2 26 | Your Task: 27 | You don't need to read input or print anything. Your task is to complete the function LCA() which takes the root Node of the BST and two integer values n1 and n2 as inputs and returns the Lowest Common Ancestor of the Nodes with values n1 and n2 in the given BST. 28 | 29 | Expected Time Complexity: O(Height of the BST). 30 | Expected Auxiliary Space: O(Height of the BST). 31 | 32 | Constraints: 33 | 1 <= N <= 104 34 | */ 35 | 36 | Node *LCA(Node *root, int n1, int n2) 37 | { 38 | if (!root) 39 | return root; 40 | if (root->data == n1 || root->data == n2) 41 | return root; 42 | 43 | if (root->data < n1 && root->data < n2) 44 | return LCA(root->right, n1, n2); 45 | else if (root->data > n1 && root->data > n2) 46 | return LCA(root->left, n1, n2); 47 | return root; 48 | } 49 | -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/Middle of Three.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Middle of Three 3 | =============== 4 | 5 | Given three distinct numbers A, B and C. Find the number with value in middle (Try to do it with minimum comparisons). 6 | 7 | Example 1: 8 | Input: 9 | A = 978, B = 518, C = 300 10 | Output: 11 | 518 12 | Explanation: 13 | Since 518>300 and 518<978, so 14 | 518 is the middle element. 15 | 16 | Example 2: 17 | Input: 18 | A = 162, B = 934, C = 200 19 | Output: 20 | 200 21 | Exaplanation: 22 | Since 200>162 && 200<934, 23 | So, 200 is the middle element. 24 | 25 | Your Task: 26 | You don't need to read input or print anything.Your task is to complete the function middle() which takes three integers A,B and C as input parameters and returns the number which has middle value. 27 | 28 | Expected Time Complexity:O(1) 29 | Expected Auxillary Space:O(1) 30 | 31 | Constraints: 32 | 1<=A,B,C<=109 33 | A,B,C are distinct. 34 | */ 35 | 36 | int middle(int A, int B, int C) 37 | { 38 | //code here//Position this line where user code will be pasted. 39 | if (A > B) 40 | { 41 | if (C > A) 42 | return A; 43 | else if (C < A && B > C) 44 | return B; 45 | else 46 | return C; 47 | } 48 | else 49 | { 50 | if (C > B) 51 | return B; 52 | else if (C < B && A > C) 53 | return A; 54 | else 55 | return C; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/Minimum element in BST.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Minimum element in BST 3 | ====================== 4 | 5 | Given a Binary Search Tree. The task is to find the minimum element in this given BST. 6 | 7 | Example 1: 8 | Input: 9 | 5 10 | / \ 11 | 4 6 12 | / \ 13 | 3 7 14 | / 15 | 1 16 | Output: 1 17 | 18 | Example 2: 19 | Input: 20 | 9 21 | \ 22 | 10 23 | \ 24 | 11 25 | Output: 9 26 | Your Task: 27 | The task is to complete the function minValue() which takes root as the argument and returns the minimum element of BST. If the tree is empty, there is no minimum elemnt, so retutn -1 in that case. 28 | 29 | Expected Time Complexity: O(Height of the BST) 30 | Expected Auxiliary Space: O(Height of the BST). 31 | 32 | Constraints: 33 | 1 <= N <= 104 34 | */ 35 | 36 | int minValue(Node *root) 37 | { 38 | if (!root->left) 39 | return root->data; 40 | return minValue(root->left); 41 | } 42 | -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/Next Permutation.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Next Permutation 3 | ================ 4 | 5 | Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. 6 | 7 | If such an arrangement is not possible, it must rearrange it as the lowest possible order (i.e., sorted in ascending order). 8 | 9 | The replacement must be in place and use only constant extra memory. 10 | 11 | Example 1: 12 | Input: nums = [1,2,3] 13 | Output: [1,3,2] 14 | 15 | Example 2: 16 | Input: nums = [3,2,1] 17 | Output: [1,2,3] 18 | 19 | Example 3: 20 | Input: nums = [1,1,5] 21 | Output: [1,5,1] 22 | 23 | Example 4: 24 | Input: nums = [1] 25 | Output: [1] 26 | 27 | Constraints: 28 | 1 <= nums.length <= 100 29 | 0 <= nums[i] <= 100 30 | */ 31 | 32 | class Solution 33 | { 34 | public: 35 | void nextPermutation(vector &nums) 36 | { 37 | int i = nums.size() - 2; 38 | while (i >= 0 && nums[i + 1] <= nums[i]) 39 | i--; 40 | 41 | if (i >= 0) 42 | { 43 | int j = nums.size() - 1; 44 | while (j >= 0 && nums[j] <= nums[i]) 45 | j--; 46 | swap(nums[i], nums[j]); 47 | } 48 | reverse(nums.begin() + i + 1, nums.end()); 49 | } 50 | }; 51 | -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/Palindrome Partitioning.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Palindrome Partitioning 3 | ======================= 4 | 5 | Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s. 6 | 7 | A palindrome string is a string that reads the same backward as forward. 8 | 9 | Example 1: 10 | Input: s = "aab" 11 | Output: [["a","a","b"],["aa","b"]] 12 | 13 | Example 2: 14 | Input: s = "a" 15 | Output: [["a"]] 16 | 17 | Constraints: 18 | 1 <= s.length <= 16 19 | s contains only lowercase English letters. 20 | */ 21 | 22 | vector> ans; 23 | bool palendrome(string &s, int st, int en) 24 | { 25 | while (st < en) 26 | { 27 | if (s[st++] != s[en--]) 28 | return false; 29 | } 30 | return true; 31 | } 32 | 33 | void dfs(string s, int st, vector &stn) 34 | { 35 | if (st == s.size()) 36 | { 37 | ans.push_back(stn); 38 | return; 39 | } 40 | 41 | for (int i = st; i < s.size(); ++i) 42 | { 43 | if (palendrome(s, st, i)) 44 | { 45 | stn.push_back(s.substr(st, i - st + 1)); 46 | dfs(s, i + 1, stn); 47 | stn.pop_back(); 48 | } 49 | } 50 | } 51 | 52 | vector> partition(string s) 53 | { 54 | ans.clear(); 55 | vector stn; 56 | 57 | dfs(s, 0, stn); 58 | 59 | return ans; 60 | } -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/Palindrome String.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Palindrome String 3 | ================= 4 | 5 | Given a string S, check if it is palindrome or not. 6 | 7 | Example 1: 8 | Input: S = "abba" 9 | Output: 1 10 | Explanation: S is a palindrome 11 | 12 | Example 2: 13 | Input: S = "abc" 14 | Output: 0 15 | Explanation: S is not a palindrome 16 | 17 | Your Task: 18 | You don't need to read input or print anything. Complete the function isPlaindrome() which accepts string S and returns a boolean value 19 | 20 | Expected Time Complexity: O(Length of S) 21 | Expected Auxiliary Space: O(1) 22 | 23 | Constraints: 24 | 1 <= Length of S <= 105 25 | */ 26 | 27 | int isPlaindrome(string s) 28 | { 29 | for (int i = 0; i < s.size() / 2; ++i) 30 | { 31 | if (s[i] != s[s.size() - 1 - i]) 32 | return 0; 33 | } 34 | return 1; 35 | } 36 | -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/Populate Inorder Successor for all nodes.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Populate Inorder Successor for all nodes 3 | =========================================== 4 | 5 | Given a Binary Tree, write a function to populate next pointer for all nodes. The next pointer for every node should be set to point to inorder successor. 6 | 7 | Example 1: 8 | Input: 9 | 10 10 | / \ 11 | 8 12 12 | / 13 | 3 14 | 15 | Output: 3->8 8->10 10->12 12->-1 16 | Explanation: The inorder of the above tree is : 17 | 3 8 10 12. So the next pointer of node 3 is 18 | pointing to 8 , next pointer of 8 is pointing 19 | to 10 and so on.And next pointer of 12 is 20 | pointing to -1 as there is no inorder successor 21 | of 12. 22 | 23 | Example 2: 24 | Input: 25 | 1 26 | / \ 27 | 2 3 28 | Output: 2->1 1->3 3->-1 29 | Your Task: 30 | You do not need to read input or print anything. Your task is to complete the function populateNext() that takes the root node of the binary tree as input parameter. 31 | 32 | Expected Time Complexity: O(N) 33 | Expected Auxiliary Space: O(N) 34 | Constraints: 35 | 1<=n<=10^5 36 | 1<=data of the node<=10^5 37 | */ 38 | 39 | Node *prev = NULL; 40 | 41 | void populateNext(Node *root) 42 | { 43 | if (!root) 44 | return; 45 | populateNext(root->right); 46 | root->next = prev; 47 | prev = root; 48 | populateNext(root->left); 49 | } -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/Queue Reversal.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Queue Reversal 3 | ============== 4 | 5 | Given a Queue Q containing N elements. The task is to reverse the Queue. Your task is to complete the function rev(), that reverses the N elements of the queue. 6 | 7 | Example 1: 8 | Input: 9 | 6 10 | 4 3 1 10 2 6 11 | Output: 12 | 6 2 10 1 3 4 13 | Explanation: 14 | After reversing the given 15 | elements of the queue , the resultant 16 | queue will be 6 2 10 1 3 4. 17 | 18 | Example 2: 19 | Input: 20 | 4 21 | 4 3 2 1 22 | Output: 23 | 1 2 3 4 24 | Explanation: 25 | After reversing the given 26 | elements of the queue , the resultant 27 | queue will be 1 2 3 4. 28 | 29 | Your Task: 30 | You only need to complete the function rev that takes a queue as parameter and returns the reversed queue. The printing is done automatically by the driver code. 31 | 32 | Expected Time Complexity : O(n) 33 | Expected Auxilliary Space : O(n) 34 | 35 | Constraints: 36 | 1 ≤ N ≤ 105 37 | 1 ≤ elements of Queue ≤ 105 38 | */ 39 | 40 | queue rev(queue q) 41 | { 42 | stack s; 43 | while (!q.empty()) 44 | { 45 | s.push(q.front()); 46 | q.pop(); 47 | } 48 | while (!s.empty()) 49 | { 50 | q.push(s.top()); 51 | s.pop(); 52 | } 53 | return q; 54 | } 55 | -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/Remove Consecutive Characters.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Remove Consecutive Characters 3 | ============================= 4 | 5 | Given a string S delete the characters which are appearing more than once consecutively. 6 | 7 | Example 1: 8 | Input: 9 | S = aabb 10 | Output: ab 11 | Explanation: 'a' at 2nd position is 12 | appearing 2nd time consecutively. 13 | Similiar explanation for b at 14 | 4th position. 15 | 16 | Example 2: 17 | Input: 18 | S = aabaa 19 | Output: aba 20 | Explanation: 'a' at 2nd position is 21 | appearing 2nd time consecutively. 22 | 'a' at fifth position is appearing 23 | 2nd time consecutively. 24 | 25 | Your Task: 26 | You dont need to read input or print anything. Complete the function removeConsecutiveCharacter() which accepts a string as input parameter and returns modified string. 27 | 28 | Expected Time Complexity: O(|S|). 29 | Expected Auxiliary Space: O(|S|). 30 | 31 | Constraints: 32 | 1<=|S|<=105 33 | All characters are lowercase alphabets. 34 | */ 35 | 36 | string removeConsecutiveCharacter(string S) 37 | { 38 | string ans; 39 | char prev = '\0'; 40 | for (auto &i : S) 41 | { 42 | if (prev == i) 43 | continue; 44 | ans += i; 45 | prev = i; 46 | } 47 | return ans; 48 | } 49 | -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/Reorganize String.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Reorganize String 3 | ================= 4 | 5 | Given a string s, rearrange the characters of s so that any two adjacent characters are not the same. 6 | 7 | Return any possible rearrangement of s or return "" if not possible. 8 | 9 | Example 1: 10 | Input: s = "aab" 11 | Output: "aba" 12 | 13 | Example 2: 14 | Input: s = "aaab" 15 | Output: "" 16 | 17 | Constraints: 18 | 1 <= s.length <= 500 19 | s consists of lowercase English letters. 20 | */ 21 | 22 | string reorganizeString(string &A) 23 | { 24 | int n = A.size(); 25 | unordered_map C; 26 | for (auto &i : A) 27 | { 28 | C[i]++; 29 | if (C[i] > (n + 1) / 2) 30 | return ""; 31 | } 32 | 33 | priority_queue> pq; 34 | for (auto &i : C) 35 | pq.push({i.second, i.first}); 36 | 37 | string B; 38 | while (pq.size()) 39 | { 40 | auto First = pq.top(); 41 | pq.pop(); 42 | auto Second = pq.top(); 43 | pq.pop(); 44 | 45 | if (First.first > 0) 46 | { 47 | B += (First.second); 48 | First.first--; 49 | } 50 | else 51 | break; 52 | 53 | if (Second.first > 0) 54 | { 55 | B += (Second.second); 56 | Second.first--; 57 | } 58 | else 59 | break; 60 | 61 | pq.push({First.first, First.second}); 62 | pq.push({Second.first, Second.second}); 63 | } 64 | 65 | return B; 66 | } -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/Reverse String.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Reverse String 3 | ============== 4 | 5 | Write a function that reverses a string. The input string is given as an array of characters char[]. 6 | 7 | Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. 8 | 9 | You may assume all the characters consist of printable ascii characters. 10 | 11 | Example 1: 12 | Input: ["h","e","l","l","o"] 13 | Output: ["o","l","l","e","h"] 14 | 15 | Example 2: 16 | Input: ["H","a","n","n","a","h"] 17 | Output: ["h","a","n","n","a","H"] 18 | */ 19 | 20 | void reverseString(vector &s) 21 | { 22 | for (int i = 0; i < s.size() / 2; ++i) 23 | swap(s[i], s[s.size() - 1 - i]); 24 | } 25 | -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/Reverse a Doubly Linked List.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Reverse a Doubly Linked List 3 | ============================ 4 | 5 | Given a doubly linked list of n elements. The task is to reverse the doubly linked list. 6 | 7 | Example 1: 8 | Input: 9 | LinkedList: 3 <--> 4 <--> 5 10 | Output: 5 4 3 11 | 12 | Example 2: 13 | Input: 14 | LinkedList: 75 <--> 122 <--> 59 <--> 196 15 | Output: 196 59 122 75 16 | 17 | Your Task: 18 | Your task is to complete the given function reverseDLL(), which takes head reference as argument and should reverse the elements so that the tail becomes the new head and all pointers are correctly pointed. You need to return the new head of the reversed list. The printing and verification is done by the driver code. 19 | 20 | Expected Time Complexity: O(n). 21 | Expected Auxiliary Space: O(1). 22 | 23 | Constraints: 24 | 1 <= number of nodes <= 103 25 | 0 <= value of nodes <= 103 26 | */ 27 | 28 | Node *reverseDLL(Node *head) 29 | { 30 | if (!head) 31 | return head; 32 | 33 | auto temp = head->next; 34 | head->next = head->prev; 35 | head->prev = temp; 36 | 37 | if (!head->prev) 38 | return head; 39 | return reverseDLL(head->prev); 40 | } -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/Reverse a linked list.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Reverse a linked list 3 | ===================== 4 | 5 | Given a linked list of N nodes. The task is to reverse this list. 6 | 7 | Example 1: 8 | Input: 9 | LinkedList: 1->2->3->4->5->6 10 | Output: 6 5 4 3 2 1 11 | Explanation: After reversing the list, 12 | elements are 6->5->4->3->2->1. 13 | 14 | Example 2: 15 | Input: 16 | LinkedList: 2->7->8->9->10 17 | Output: 10 9 8 7 2 18 | Explanation: After reversing the list, 19 | elements are 10->9->8->7->2. 20 | Your Task: 21 | The task is to complete the function reverseList() with head reference as the only argument and should return new head after reversing the list. 22 | 23 | Expected Time Complexity: O(N). 24 | Expected Auxiliary Space: O(1). 25 | 26 | Constraints: 27 | 1 <= N <= 104 28 | */ 29 | 30 | struct Node *reverseList(struct Node *head) 31 | { 32 | if (!head || !head->next) 33 | return head; 34 | Node *rest = reverseList(head->next); 35 | head->next->next = head; 36 | head->next = NULL; 37 | return rest; 38 | } 39 | -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/Reverse a string using Stack.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Reverse a string using Stack 3 | ============================ 4 | 5 | You are given a string S, the task is to reverse the string using stack. 6 | 7 | Example 1: 8 | Input: S="GeeksforGeeks" 9 | Output: skeeGrofskeeG 10 | 11 | Your Task: 12 | You don't need to read input or print anything. Your task is to complete the function reverse() which takes the string S as an input parameter and returns the reversed string. 13 | 14 | Expected Time Complexity: O(N) 15 | Expected Auxiliary Space: O(N) 16 | 17 | Constraints: 18 | 1 ≤ length of the string ≤ 100 19 | */ 20 | 21 | char *reverse(char *S, int len) 22 | { 23 | char *ans = new char[len + 1]; 24 | stack st; 25 | for (int i = 0; i < len && S[i] != '\0'; ++i) 26 | st.push(S[i]); 27 | int i; 28 | for (i = 0; i < len; ++i) 29 | { 30 | ans[i] = st.top(); 31 | st.pop(); 32 | } 33 | ans[i] = '\0'; 34 | return ans; 35 | } 36 | -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/Search a 2D Matrix.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Search a 2D Matrix 3 | ================== 4 | 5 | Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: 6 | 7 | Integers in each row are sorted from left to right. 8 | The first integer of each row is greater than the last integer of the previous row. 9 | 10 | Example 1: 11 | Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 12 | Output: true 13 | 14 | Example 2: 15 | Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13 16 | Output: false 17 | 18 | Constraints: 19 | m == matrix.length 20 | n == matrix[i].length 21 | 1 <= m, n <= 100 22 | -104 <= matrix[i][j], target <= 104 23 | */ 24 | 25 | class Solution 26 | { 27 | public: 28 | bool searchMatrix(vector> &matrix, int target) 29 | { 30 | int n = matrix.size(), m = matrix[0].size(); 31 | int r = 0, c = m - 1; 32 | 33 | while (r < n && c >= 0) 34 | { 35 | if (matrix[r][c] == target) 36 | return true; 37 | else if (matrix[r][c] < target) 38 | r++; 39 | else 40 | c--; 41 | } 42 | return false; 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/Sort an array of 0s, 1s and 2s.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Sort an array of 0s, 1s and 2s 3 | ============================== 4 | 5 | Given an array of size N containing only 0s, 1s, and 2s; sort the array in ascending order. 6 | 7 | Example 1: 8 | Input: 9 | N = 5 10 | arr[]= {0 2 1 2 0} 11 | Output: 12 | 0 0 1 2 2 13 | Explanation: 14 | 0s 1s and 2s are segregated 15 | into ascending order. 16 | 17 | Example 2: 18 | Input: 19 | N = 3 20 | arr[] = {0 1 0} 21 | Output: 22 | 0 0 1 23 | Explanation: 24 | 0s 1s and 2s are segregated 25 | into ascending order. 26 | 27 | Your Task: 28 | You don't need to read input or print anything. Your task is to complete the function sort012() that takes an array arr and N as input parameters and sorts the array in-place. 29 | 30 | Expected Time Complexity: O(N) 31 | Expected Auxiliary Space: O(1) 32 | 33 | Constraints: 34 | 1 <= N <= 10^5 35 | 0 <= A[i] <= 2 36 | */ 37 | 38 | void sort012(int a[], int n) 39 | { 40 | vector count(3, 0); 41 | for (int i = 0; i < n; ++i) 42 | count[a[i]]++; 43 | for (int i = 0; i < n; ++i) 44 | { 45 | if (count[0]) 46 | { 47 | a[i] = 0; 48 | count[0]--; 49 | } 50 | else if (count[1]) 51 | { 52 | a[i] = 1; 53 | count[1]--; 54 | } 55 | else 56 | { 57 | a[i] = 2; 58 | count[2]--; 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/Sorted matrix.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Sorted matrix 3 | ============= 4 | 5 | Given an NxN matrix Mat. Sort all elements of the matrix. 6 | 7 | Example 1: 8 | Input: 9 | N=4 10 | Mat=[[10,20,30,40], 11 | [15,25,35,45] 12 | [27,29,37,48] 13 | [32,33,39,50]] 14 | Output: 15 | 10 15 20 25 16 | 27 29 30 32 17 | 33 35 37 39 18 | 40 45 48 50 19 | Explanation: 20 | Sorting the matrix gives this result. 21 | 22 | Example 2: 23 | Input: 24 | N=3 25 | Mat=[[1,5,3],[2,8,7],[4,6,9]] 26 | Output: 27 | 1 2 3 28 | 4 5 6 29 | 7 8 9 30 | Explanation: 31 | Sorting the matrix gives this result. 32 | Your Task: 33 | You don't need to read input or print anything. Your task is to complete the function sortedMatrix() which takes the integer N and the matrix Mat as input parameters and returns the sorted matrix. 34 | 35 | Expected Time Complexity:O(N2LogN) 36 | Expected Auxillary Space:O(N2) 37 | 38 | Constraints: 39 | 1<=N<=1000 40 | 1<=Mat[i][j]<=105 41 | */ 42 | 43 | vector> sortedMatrix(int N, vector> Mat) 44 | { 45 | vector sorted; 46 | for (auto &row : Mat) 47 | { 48 | for (auto &i : row) 49 | sorted.push_back(i); 50 | } 51 | sort(sorted.begin(), sorted.end()); 52 | int i = 0; 53 | for (auto &row : Mat) 54 | { 55 | for (auto &e : row) 56 | { 57 | e = sorted[i]; 58 | i++; 59 | } 60 | } 61 | return Mat; 62 | } 63 | -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/Subarray with 0 sum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Subarray with 0 sum 3 | ==================== 4 | 5 | Given an array of positive and negative numbers. Find if there is a subarray (of size at-least one) with 0 sum. 6 | 7 | Example 1: 8 | Input: 9 | 5 10 | 4 2 -3 1 6 11 | Output: 12 | Yes 13 | Explanation: 14 | 2, -3, 1 is the subarray 15 | with sum 0. 16 | 17 | Example 2: 18 | Input: 19 | 5 20 | 4 2 0 1 6 21 | Output: 22 | Yes 23 | Explanation: 24 | 0 is one of the element 25 | in the array so there exist a 26 | subarray with sum 0. 27 | Your Task: 28 | You only need to complete the function subArrayExists() that takes array and n as parameters and returns true or false depending upon whether there is a subarray present with 0-sum or not. Printing will be taken care by the drivers code. 29 | 30 | Expected Time Complexity: O(n). 31 | Expected Auxiliary Space: O(n). 32 | 33 | Constraints: 34 | 1 <= N <= 104 35 | -105 <= a[i] <= 105 36 | */ 37 | 38 | bool subArrayExists(int arr[], int n) 39 | { 40 | unordered_set prefix_sums; 41 | int sum = 0; 42 | for (int i = 0; i < n; ++i) 43 | { 44 | sum += arr[i]; 45 | if (!sum) 46 | return true; 47 | if (prefix_sums.find(sum) != prefix_sums.end()) 48 | return true; 49 | prefix_sums.insert(sum); 50 | } 51 | return false; 52 | } 53 | -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/Valid Substring.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Valid Substring 3 | =============== 4 | 5 | Given a string S consisting only of opening and closing parenthesis 'ie '(' and ')', find out the length of the longest valid(well-formed) parentheses substring. 6 | NOTE: Length of smallest the valid substring ( ) is 2. 7 | 8 | Example 1: 9 | Input: S = "(()(" 10 | Output: 2 11 | Explanation: The longest valid 12 | substring is "()". Length = 2. 13 | 14 | Example 2: 15 | Input: S = "()(())(" 16 | Output: 6 17 | Explanation: The longest valid 18 | substring is "()(())". Length = 6. 19 | 20 | Your Task: 21 | You dont need to read input or print anything. Complete the function findMaxLen() which takes S as input parameter and returns the maxlength. 22 | 23 | Expected Time Complexity:O(n) 24 | Expected Auxiliary Space: O(1) 25 | 26 | Constraints: 27 | 1 <= |S| <= 105 28 | */ 29 | 30 | int findMaxLen(string s) 31 | { 32 | stack si; 33 | si.push(-1); 34 | 35 | int ans = 0; 36 | 37 | for (int i = 0; i < s.size(); ++i) 38 | { 39 | if (s[i] == '(') 40 | si.push(i); 41 | else 42 | { 43 | si.pop(); 44 | if (si.size()) 45 | { 46 | int curr = i - si.top(); 47 | ans = max(ans, curr); 48 | } 49 | else 50 | si.push(i); 51 | } 52 | } 53 | return ans; 54 | } 55 | -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/Value equal to index value.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Value equal to index value 3 | ========================== 4 | 5 | Given an array Arr of N positive integers. Your task is to find the elements whose value is equal to that of its index value. 6 | 7 | Example 1: 8 | 9 | Input: 10 | N = 5 11 | Arr[] = {15, 2, 45, 12, 7} 12 | Output: 2 13 | Explanation: Only Arr[2] = 2 exists here. 14 | 15 | Example 2: 16 | Input: 17 | N = 1 18 | Arr[] = {1} 19 | Output: 1 20 | Explanation: Here Arr[1] = 1 exists. 21 | Your Task: 22 | You don't need to read input or print anything. Your task is to complete the function valueEqualToIndex() which takes the array of integers arr[] and n as parameters and returns an array of indices where the given conditions are satified. When there is not such element exists then return an empty array of length 0. 23 | 24 | Expected Time Complexity: O(N) 25 | Expected Auxiliary Space: O(1) 26 | Note: There can be more than one element in the array which have same value as their index. You need to include every such element's index. Follows 1-based indexing of the array. 27 | 28 | Constraints: 29 | 1 ≤ N ≤ 105 30 | 1 ≤ Arr[i] ≤ 106 31 | */ 32 | 33 | vector valueEqualToIndex(int arr[], int n) 34 | { 35 | vector ans; 36 | for (int i = 0; i < n; ++i) 37 | { 38 | if (i + 1 == arr[i]) 39 | ans.push_back(i + 1); 40 | } 41 | return ans; 42 | } 43 | -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/Zero Sum Subarrays.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Zero Sum Subarrays 3 | ================== 4 | 5 | You are given an array arr[] of size n. Find the total count of sub-arrays having their sum equal to 0. 6 | 7 | Example 1: 8 | Input: 9 | n = 6 10 | arr[] = {0,0,5,5,0,0} 11 | Output: 6 12 | Explanation: The 6 subarrays are 13 | [0], [0], [0], [0], [0,0], and [0,0]. 14 | 15 | Example 2: 16 | Input: 17 | n = 10 18 | arr[] = {6,-1,-3,4,-2,2,4,6,-12,-7} 19 | Output: 4 20 | Explanation: The 4 subarrays are [-1 -3 4] 21 | [-2 2], [2 4 6 -12], and [-1 -3 4 -2 2] 22 | 23 | Your Task: 24 | You don't need to read input or print anything. Complete the function findSubarray() that takes the array arr and its size n as input parameters and returns the total number of sub-arrays with 0 sum. 25 | 26 | Expected Time Complexity : O(n) 27 | Expected Auxilliary Space : O(n) 28 | 29 | Constraints: 30 | 1<= n <= 107 31 | -1010 <= arri <= 1010 32 | */ 33 | 34 | //User function template for C++ 35 | 36 | // arr : given array 37 | // n : size of the given array 38 | ll findSubarray(vector arr, int n) 39 | { 40 | unordered_map> sums; 41 | ll sum = 0; 42 | ll ans = 0; 43 | for (int i = 0; i < n; ++i) 44 | { 45 | sum += arr[i]; 46 | if (sum == 0) 47 | ans++; 48 | if (sums.find(sum) != sums.end()) 49 | ans += sums[sum].size(); 50 | sums[sum].push_back(i); 51 | } 52 | return ans; 53 | } 54 | -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/k largest elements.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | k largest elements 3 | ================== 4 | 5 | Given an array Arr of N positive integers, find K largest elements from the array. The output elements should be printed in decreasing order. 6 | 7 | Example 1: 8 | Input: 9 | N = 5, K = 2 10 | Arr[] = {12, 5, 787, 1, 23} 11 | Output: 787 23 12 | Explanation: 1st largest element in the 13 | array is 787 and second largest is 23. 14 | 15 | Example 2: 16 | Input: 17 | N = 7, K = 3 18 | Arr[] = {1, 23, 12, 9, 30, 2, 50} 19 | Output: 50 30 23 20 | Explanation: 3 Largest element in the 21 | array are 50, 30 and 23. 22 | Your Task: 23 | You don't need to read input or print anything. Your task is to complete the function kLargest() which takes the array of integers arr, n and k as parameters and returns an array of integers denoting the answer. The array should be in decreasing order. 24 | 25 | Expected Time Complexity: O(N) 26 | Expected Auxiliary Space: O(K*logK) 27 | 28 | Constraints: 29 | 1 ≤ K ≤ N ≤ 105 30 | 1 ≤ Arr[i] ≤ 106 31 | 32 | */ 33 | 34 | vector kLargest(int arr[], int n, int k) 35 | { 36 | vector ans; 37 | priority_queue pq; 38 | for (int i = 0; i < n; ++i) 39 | pq.push(arr[i]); 40 | 41 | for (int i = 0; i < k; ++i) 42 | { 43 | ans.push_back(pq.top()); 44 | pq.pop(); 45 | } 46 | 47 | return ans; 48 | } -------------------------------------------------------------------------------- /DSA Crack Sheet/solutions/k-th smallest element in BST.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | k-th smallest element in BST 3 | ============================ 4 | 5 | Given a BST and an integer K. Find the Kth Smallest element in the BST. 6 | 7 | Example 1: 8 | Input: 9 | 2 10 | / \ 11 | 1 3 12 | K = 2 13 | Output: 2 14 | 15 | Example 2: 16 | Input: 17 | 2 18 | / \ 19 | 1 3 20 | K = 5 21 | Output: -1 22 | 23 | 24 | Your Task: 25 | You don't need to read input or print anything. Your task is to complete the function KthSmallestElement() which takes the root of the BST and integer K as inputs and return the Kth smallest element in the BST, if no such element exists return -1. 26 | 27 | Expected Time Complexity: O(N). 28 | Expected Auxiliary Space: O(1). 29 | 30 | Constraints: 31 | 1<=Number of nodes<=100000 32 | */ 33 | 34 | int ans = -1; 35 | void inorder(Node *root, int &k) 36 | { 37 | if (k == 0 || !root) 38 | return; 39 | inorder(root->left, k); 40 | k--; 41 | if (k == 0) 42 | { 43 | ans = root->data; 44 | return; 45 | } 46 | inorder(root->right, k); 47 | } 48 | 49 | // Return the Kth smallest element in the given BST 50 | int KthSmallestElement(Node *root, int K) 51 | { 52 | //add code here. 53 | inorder(root, K); 54 | return ans; 55 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 sachin verma 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/April-2021/03. Longest Valid Parentheses.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Longest Valid Parentheses 3 | ========================= 4 | 5 | Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. 6 | 7 | Example 1: 8 | Input: s = "(()" 9 | Output: 2 10 | Explanation: The longest valid parentheses substring is "()". 11 | 12 | Example 2: 13 | Input: s = ")()())" 14 | Output: 4 15 | Explanation: The longest valid parentheses substring is "()()". 16 | 17 | Example 3: 18 | Input: s = "" 19 | Output: 0 20 | 21 | Constraints: 22 | 0 <= s.length <= 3 * 104 23 | s[i] is '(', or ')'. 24 | */ 25 | 26 | class Solution 27 | { 28 | public: 29 | int longestValidParentheses(string s) 30 | { 31 | int ans = 0; 32 | stack sc; 33 | stack si; 34 | si.push(-1); 35 | 36 | for (int i = 0; i < s.size(); ++i) 37 | { 38 | char ch = s[i]; 39 | if (ch == ')') 40 | { 41 | if (sc.size() && sc.top() == '(') 42 | { 43 | sc.pop(); 44 | si.pop(); 45 | 46 | int curr = i - si.top(); 47 | // si.push(i); 48 | ans = max(ans, curr); 49 | } 50 | else 51 | si.push(i); 52 | } 53 | else 54 | { 55 | sc.push(ch); 56 | si.push(i); 57 | } 58 | } 59 | 60 | return ans; 61 | } 62 | }; 63 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/April-2021/05. Global and Local Inversions.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Global and Local Inversions 3 | =========================== 4 | 5 | We have some permutation A of [0, 1, ..., N - 1], where N is the length of A. 6 | 7 | The number of (global) inversions is the number of i < j with 0 <= i < j < N and A[i] > A[j]. 8 | 9 | The number of local inversions is the number of i with 0 <= i < N and A[i] > A[i+1]. 10 | 11 | Return true if and only if the number of global inversions is equal to the number of local inversions. 12 | 13 | Example 1: 14 | Input: A = [1,0,2] 15 | Output: true 16 | Explanation: There is 1 global inversion, and 1 local inversion. 17 | 18 | Example 2: 19 | Input: A = [1,2,0] 20 | Output: false 21 | Explanation: There are 2 global inversions, and 1 local inversion. 22 | Note: 23 | 24 | A will be a permutation of [0, 1, ..., A.length - 1]. 25 | A will have length in range [1, 5000]. 26 | The time limit for this problem has been reduced. 27 | 28 | Hint #1 29 | Where can the 0 be placed in an ideal permutation? What about the 1? 30 | */ 31 | 32 | class Solution 33 | { 34 | public: 35 | bool isIdealPermutation(vector &A) 36 | { 37 | if (A.size() <= 1) 38 | return true; 39 | int Max = -1; 40 | for (int i = 0; i < A.size() - 2; ++i) 41 | { 42 | Max = max(Max, A[i]); 43 | if (Max > A[i + 2]) 44 | return false; 45 | } 46 | return true; 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/April-2021/15. Fibonacci Number.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Fibonacci Number 3 | ================ 4 | 5 | The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, 6 | 7 | F(0) = 0, F(1) = 1 8 | F(n) = F(n - 1) + F(n - 2), for n > 1. 9 | Given n, calculate F(n). 10 | 11 | Example 1: 12 | Input: n = 2 13 | Output: 1 14 | Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1. 15 | 16 | Example 2: 17 | Input: n = 3 18 | Output: 2 19 | Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2. 20 | 21 | Example 3: 22 | Input: n = 4 23 | Output: 3 24 | Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3. 25 | 26 | Constraints: 27 | 0 <= n <= 30 28 | */ 29 | 30 | class Solution 31 | { 32 | public: 33 | int fib(int n) 34 | { 35 | if (n <= 1) 36 | return n; 37 | 38 | vector fibb(n + 1, 0); 39 | fibb[0] = 0; 40 | fibb[1] = 1; 41 | 42 | for (int i = 2; i <= n; ++i) 43 | { 44 | fibb[i] = fibb[i - 1] + fibb[i - 2]; 45 | } 46 | return fibb[n]; 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/April-2021/25. Rotate Image.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Rotate Image 3 | ============ 4 | 5 | You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). 6 | 7 | You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. 8 | 9 | Example 1: 10 | Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] 11 | Output: [[7,4,1],[8,5,2],[9,6,3]] 12 | 13 | Example 2: 14 | Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] 15 | Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]] 16 | 17 | Example 3: 18 | Input: matrix = [[1]] 19 | Output: [[1]] 20 | 21 | Example 4: 22 | Input: matrix = [[1,2],[3,4]] 23 | Output: [[3,1],[4,2]] 24 | 25 | Constraints: 26 | matrix.length == n 27 | matrix[i].length == n 28 | 1 <= n <= 20 29 | -1000 <= matrix[i][j] <= 1000 30 | */ 31 | 32 | class Solution 33 | { 34 | public: 35 | void rotate(vector> &matrix) 36 | { 37 | for (int i = 0; i < matrix.size(); ++i) 38 | { 39 | for (int j = i; j < matrix.size(); ++j) 40 | { 41 | swap(matrix[i][j], matrix[j][i]); 42 | } 43 | } 44 | 45 | for (int i = 0; i < matrix.size(); ++i) 46 | { 47 | for (int j = 0; j < matrix.size() / 2; ++j) 48 | { 49 | swap(matrix[i][j], matrix[i][matrix.size() - j - 1]); 50 | } 51 | } 52 | } 53 | }; 54 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/April-2021/27. Power of Three.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Power of Three 3 | ============= 4 | 5 | Given an integer n, return true if it is a power of three. Otherwise, return false. 6 | 7 | An integer n is a power of three, if there exists an integer x such that n == 3x. 8 | 9 | Example 1: 10 | Input: n = 27 11 | Output: true 12 | 13 | Example 2: 14 | Input: n = 0 15 | Output: false 16 | 17 | Example 3: 18 | Input: n = 9 19 | Output: true 20 | 21 | Example 4: 22 | Input: n = 45 23 | Output: false 24 | 25 | Constraints: 26 | -231 <= n <= 231 - 1 27 | 28 | Follow up: Could you solve it without loops/recursion? 29 | */ 30 | 31 | class Solution 32 | { 33 | public: 34 | bool isPowerOfThree(int n) 35 | { 36 | long max3Num = pow(3, (int)(log10(INT_MAX) / log10(3))); 37 | return n > 0 && max3Num % n == 0; 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/April-2021/30. Powerful Integers.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Powerful Integers 3 | ================= 4 | 5 | Given three integers x, y, and bound, return a list of all the powerful integers that have a value less than or equal to bound. 6 | 7 | An integer is powerful if it can be represented as xi + yj for some integers i >= 0 and j >= 0. 8 | 9 | You may return the answer in any order. In your answer, each value should occur at most once. 10 | 11 | Example 1: 12 | Input: x = 2, y = 3, bound = 10 13 | Output: [2,3,4,5,7,9,10] 14 | Explanation: 15 | 2 = 20 + 30 16 | 3 = 21 + 30 17 | 4 = 20 + 31 18 | 5 = 21 + 31 19 | 7 = 22 + 31 20 | 9 = 23 + 30 21 | 10 = 20 + 32 22 | 23 | Example 2: 24 | Input: x = 3, y = 5, bound = 15 25 | Output: [2,4,6,8,10,14] 26 | 27 | Constraints: 28 | 1 <= x, y <= 100 29 | 0 <= bound <= 106 30 | */ 31 | 32 | class Solution 33 | { 34 | public: 35 | vector powerfulIntegers(int x, int y, int bound) 36 | { 37 | unordered_set s; 38 | for (int i = 1; i <= bound; i = i * x) 39 | { 40 | for (int j = 1; i + j <= bound; j = j * y) 41 | { 42 | s.insert(i + j); 43 | if (y == 1) 44 | break; 45 | } 46 | if (x == 1) 47 | break; 48 | } 49 | return vector(s.begin(), s.end()); 50 | } 51 | }; 52 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/August-2021/03. Subsets II.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Subsets II 3 | ========== 4 | 5 | Given an integer array nums that may contain duplicates, return all possible subsets (the power set). 6 | 7 | The solution set must not contain duplicate subsets. Return the solution in any order. 8 | 9 | Example 1: 10 | Input: nums = [1,2,2] 11 | Output: [[],[1],[1,2],[1,2,2],[2],[2,2]] 12 | 13 | Example 2: 14 | Input: nums = [0] 15 | Output: [[],[0]] 16 | 17 | Constraints: 18 | 1 <= nums.length <= 10 19 | -10 <= nums[i] <= 10 20 | */ 21 | 22 | class Solution 23 | { 24 | public: 25 | void dfs(vector &nums, int i, vector atn, set> &ans) 26 | { 27 | if (i == nums.size()) 28 | { 29 | sort(atn.begin(), atn.end()); 30 | ans.insert(atn); 31 | return; 32 | } 33 | 34 | dfs(nums, i + 1, atn, ans); 35 | atn.push_back(nums[i]); 36 | dfs(nums, i + 1, atn, ans); 37 | } 38 | 39 | vector> subsetsWithDup(vector &nums) 40 | { 41 | set> sans; 42 | dfs(nums, 0, {}, sans); 43 | vector> ans; 44 | for (auto &i : sans) 45 | ans.push_back(i); 46 | return ans; 47 | } 48 | }; -------------------------------------------------------------------------------- /Leetcode Daily Challenge/August-2021/12. Group Anagrams.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Group Anagrams 3 | ============== 4 | 5 | Given an array of strings strs, group the anagrams together. You can return the answer in any order. 6 | 7 | An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. 8 | 9 | Example 1: 10 | Input: strs = ["eat","tea","tan","ate","nat","bat"] 11 | Output: [["bat"],["nat","tan"],["ate","eat","tea"]] 12 | 13 | Example 2: 14 | Input: strs = [""] 15 | Output: [[""]] 16 | 17 | Example 3: 18 | Input: strs = ["a"] 19 | Output: [["a"]] 20 | 21 | Constraints: 22 | 1 <= strs.length <= 104 23 | 0 <= strs[i].length <= 100 24 | strs[i] consists of lower-case English letters. 25 | */ 26 | 27 | class Solution 28 | { 29 | public: 30 | vector> groupAnagrams(vector &S) 31 | { 32 | unordered_map> strs; 33 | 34 | for (auto &i : S) 35 | { 36 | auto sorted = i; 37 | sort(sorted.begin(), sorted.end()); 38 | strs[sorted].push_back(i); 39 | } 40 | 41 | vector> ans; 42 | for (auto &i : strs) 43 | ans.push_back(i.second); 44 | 45 | return ans; 46 | } 47 | }; -------------------------------------------------------------------------------- /Leetcode Daily Challenge/August-2021/24. Complex Number Multiplication.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Complex Number Multiplication 3 | ============================= 4 | 5 | A complex number can be represented as a string on the form "real+imaginaryi" where: 6 | 7 | real is the real part and is an integer in the range [-100, 100]. 8 | imaginary is the imaginary part and is an integer in the range [-100, 100]. 9 | i2 == -1. 10 | Given two complex numbers num1 and num2 as strings, return a string of the complex number that represents their multiplications. 11 | 12 | Example 1: 13 | Input: num1 = "1+1i", num2 = "1+1i" 14 | Output: "0+2i" 15 | Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i. 16 | 17 | Example 2: 18 | Input: num1 = "1+-1i", num2 = "1+-1i" 19 | Output: "0+-2i" 20 | Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i. 21 | 22 | Constraints: 23 | num1 and num2 are valid complex numbers. 24 | */ 25 | 26 | class Solution { 27 | public: 28 | string complexNumberMultiply(string a, string b) { 29 | int r1 = stoi(a.substr(0, a.find('+')+1)); 30 | int r2 = stoi(b.substr(0, b.find('+')+1)); 31 | 32 | int c1 = stoi(a.substr(a.find('+')+1)); 33 | int c2 = stoi(b.substr(b.find('+')+1)); 34 | 35 | return to_string(r1*r2 - c1*c2) + "+" + to_string(r1*c2 + r2*c1) + "i"; 36 | } 37 | }; -------------------------------------------------------------------------------- /Leetcode Daily Challenge/August-2021/25. Sum of Square Numbers.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Sum of Square Numbers 3 | ===================== 4 | 5 | Given a non-negative integer c, decide whether there're two integers a and b such that a2 + b2 = c. 6 | 7 | Example 1: 8 | Input: c = 5 9 | Output: true 10 | Explanation: 1 * 1 + 2 * 2 = 5 11 | 12 | Example 2: 13 | Input: c = 3 14 | Output: false 15 | 16 | Example 3: 17 | Input: c = 4 18 | Output: true 19 | 20 | Example 4: 21 | Input: c = 2 22 | Output: true 23 | 24 | Example 5: 25 | Input: c = 1 26 | Output: true 27 | 28 | Constraints: 29 | 0 <= c <= 231 - 1 30 | */ 31 | 32 | class Solution { 33 | public: 34 | bool judgeSquareSum(int c) { 35 | int sqrt_c = sqrt(c); 36 | if(sqrt_c * sqrt_c == c) return true; 37 | 38 | for(int a = 0; a <= sqrt(c); ++a) { 39 | int b_sq = c - (a*a); 40 | int b = sqrt(b_sq); 41 | if(b*b == b_sq) return true; 42 | } 43 | 44 | return false; 45 | } 46 | }; -------------------------------------------------------------------------------- /Leetcode Daily Challenge/August-2021/30. Range Addition II.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Range Addition II 3 | ================= 4 | 5 | You are given an m x n matrix M initialized with all 0's and an array of operations ops, where ops[i] = [ai, bi] means M[x][y] should be incremented by one for all 0 <= x < ai and 0 <= y < bi. 6 | 7 | Count and return the number of maximum integers in the matrix after performing all the operations. 8 | 9 | Example 1: 10 | Input: m = 3, n = 3, ops = [[2,2],[3,3]] 11 | Output: 4 12 | Explanation: The maximum integer in M is 2, and there are four of it in M. So return 4. 13 | 14 | Example 2: 15 | Input: m = 3, n = 3, ops = [[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3]] 16 | Output: 4 17 | 18 | Example 3: 19 | Input: m = 3, n = 3, ops = [] 20 | Output: 9 21 | 22 | Constraints: 23 | 1 <= m, n <= 4 * 104 24 | 1 <= ops.length <= 104 25 | ops[i].length == 2 26 | 1 <= ai <= m 27 | 1 <= bi <= n 28 | */ 29 | 30 | class Solution { 31 | public: 32 | int maxCount(int m, int n, vector>& ops) { 33 | for(auto& op: ops) { 34 | m = min(m, op[0]); 35 | n = min(n, op[1]); 36 | } 37 | 38 | return m*n; 39 | } 40 | }; -------------------------------------------------------------------------------- /Leetcode Daily Challenge/December-2020/05. Can Place Flowers.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Can Place Flowers 3 | ================= 4 | 5 | You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots. 6 | 7 | Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an integer n, return if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule. 8 | 9 | 10 | Example 1: 11 | Input: flowerbed = [1,0,0,0,1], n = 1 12 | Output: true 13 | 14 | Example 2: 15 | Input: flowerbed = [1,0,0,0,1], n = 2 16 | Output: false 17 | 18 | Constraints: 19 | 1 <= flowerbed.length <= 2 * 104 20 | flowerbed[i] is 0 or 1. 21 | There are no two adjacent flowers in flowerbed. 22 | 0 <= n <= flowerbed.length 23 | */ 24 | 25 | class Solution 26 | { 27 | public: 28 | bool canPlaceFlowers(vector &flowerbed, int k) 29 | { 30 | int n = flowerbed.size(), ans = 0; 31 | for (int i = 0; i < n; ++i) 32 | { 33 | if (flowerbed[i] == 0) 34 | { 35 | int prev = i == 0 ? 0 : flowerbed[i - 1]; 36 | int next = i == n - 1 ? 0 : flowerbed[i + 1]; 37 | if (prev == 0 && next == 0) 38 | { 39 | flowerbed[i] = 1; 40 | ans++; 41 | } 42 | } 43 | } 44 | 45 | return ans >= k; 46 | } 47 | }; 48 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/December-2020/15. Squares of a Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Squares of a Sorted Array 3 | ========================= 4 | 5 | Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order. 6 | 7 | Example 1: 8 | Input: nums = [-4,-1,0,3,10] 9 | Output: [0,1,9,16,100] 10 | Explanation: After squaring, the array becomes [16,1,0,9,100]. 11 | After sorting, it becomes [0,1,9,16,100]. 12 | 13 | Example 2: 14 | Input: nums = [-7,-3,2,3,11] 15 | Output: [4,9,9,49,121] 16 | 17 | Constraints: 18 | 1 <= nums.length <= 104 19 | -104 <= nums[i] <= 104 20 | nums is sorted in non-decreasing order. 21 | */ 22 | 23 | class Solution 24 | { 25 | public: 26 | vector sortedSquares(vector &nums) 27 | { 28 | vector ans; 29 | int i = 0, j = nums.size() - 1; 30 | while (i <= j) 31 | { 32 | if (nums[i] * nums[i] > nums[j] * nums[j]) 33 | { 34 | ans.insert(ans.begin(), nums[i] * nums[i]); 35 | i++; 36 | } 37 | else 38 | { 39 | ans.insert(ans.begin(), nums[j] * nums[j]); 40 | j--; 41 | } 42 | } 43 | return ans; 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/December-2020/17. 4Sum II.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 4Sum II 3 | ======= 4 | 5 | Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero. 6 | 7 | To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -228 to 228 - 1 and the result is guaranteed to be at most 231 - 1. 8 | 9 | Example: 10 | Input: 11 | A = [ 1, 2] 12 | B = [-2,-1] 13 | C = [-1, 2] 14 | D = [ 0, 2] 15 | Output: 16 | 2 17 | 18 | Explanation: 19 | The two tuples are: 20 | 1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0 21 | 2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0 22 | */ 23 | 24 | class Solution 25 | { 26 | public: 27 | int fourSumCount(vector &A, vector &B, vector &C, vector &D) 28 | { 29 | unordered_map abSum; 30 | for (auto a : A) 31 | { 32 | for (auto b : B) 33 | { 34 | ++abSum[a + b]; 35 | } 36 | } 37 | int count = 0; 38 | for (auto c : C) 39 | { 40 | for (auto d : D) 41 | { 42 | auto it = abSum.find(0 - c - d); 43 | if (it != abSum.end()) 44 | { 45 | count += it->second; 46 | } 47 | } 48 | } 49 | return count; 50 | } 51 | }; 52 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/December-2020/21. Smallest Range II.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Smallest Range II 3 | ================= 4 | 5 | Given an array A of integers, for each integer A[i] we need to choose either x = -K or x = K, and add x to A[i] (only once). 6 | 7 | After this process, we have some array B. 8 | 9 | Return the smallest possible difference between the maximum value of B and the minimum value of B. 10 | 11 | Example 1: 12 | Input: A = [1], K = 0 13 | Output: 0 14 | Explanation: B = [1] 15 | 16 | Example 2: 17 | Input: A = [0,10], K = 2 18 | Output: 6 19 | Explanation: B = [2,8] 20 | 21 | Example 3: 22 | Input: A = [1,3,6], K = 3 23 | Output: 3 24 | Explanation: B = [4,6,3] 25 | 26 | Note: 27 | 1 <= A.length <= 10000 28 | 0 <= A[i] <= 10000 29 | 0 <= K <= 10000 30 | */ 31 | 32 | class Solution 33 | { 34 | public: 35 | int smallestRangeII(vector &A, int K) 36 | { 37 | sort(A.begin(), A.end()); 38 | int ans = -A[0] + A[A.size() - 1]; 39 | for (int i = 0; i < A.size() - 1; ++i) 40 | { 41 | int j = i + 1; 42 | int low = min(A[0] + K, A[j] - K); 43 | int high = max(A[A.size() - 1] - K, A[i] + K); 44 | ans = min(ans, high - low); 45 | } 46 | return ans; 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/December-2020/23. Next Greater Element III.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Next Greater Element III 3 | ======================== 4 | 5 | Given a positive integer n, find the smallest integer which has exactly the same digits existing in the integer n and is greater in value than n. If no such positive integer exists, return -1. 6 | 7 | Note that the returned integer should fit in 32-bit integer, if there is a valid answer but it does not fit in 32-bit integer, return -1. 8 | 9 | Example 1: 10 | Input: n = 12 11 | Output: 21 12 | 13 | Example 2: 14 | Input: n = 21 15 | Output: -1 16 | 17 | Constraints: 18 | 1 <= n <= 231 - 1 19 | */ 20 | 21 | class Solution 22 | { 23 | public: 24 | int nextGreaterElement(int n) 25 | { 26 | vector digits; 27 | while (n) 28 | { 29 | int digit = n % 10; 30 | digits.insert(digits.begin(), digit); 31 | n /= 10; 32 | } 33 | 34 | if (next_permutation(digits.begin(), digits.end())) 35 | { 36 | long long number = 0; 37 | 38 | for (int i = 0; i < digits.size(); ++i) 39 | number = number * 10 + digits[i]; 40 | 41 | if (number > INT_MAX) 42 | return -1; 43 | return number; 44 | } 45 | else 46 | return -1; 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/December-2020/24. Swap Nodes in Pairs.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Swap Nodes in Pairs 3 | =================== 4 | 5 | Given a linked list, swap every two adjacent nodes and return its head. 6 | You may not modify the values in the list's nodes. Only nodes itself may be changed. 7 | 8 | Example 1: 9 | Input: head = [1,2,3,4] 10 | Output: [2,1,4,3] 11 | 12 | Example 2: 13 | Input: head = [] 14 | Output: [] 15 | 16 | Example 3: 17 | Input: head = [1] 18 | Output: [1] 19 | 20 | Constraints: 21 | The number of nodes in the list is in the range [0, 100]. 22 | 0 <= Node.val <= 100 23 | */ 24 | 25 | /** 26 | * Definition for singly-linked list. 27 | * struct ListNode { 28 | * int val; 29 | * ListNode *next; 30 | * ListNode() : val(0), next(nullptr) {} 31 | * ListNode(int x) : val(x), next(nullptr) {} 32 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 33 | * }; 34 | */ 35 | 36 | class Solution 37 | { 38 | public: 39 | ListNode *swapPairs(ListNode *head) 40 | { 41 | if (!head || !head->next) 42 | return head; 43 | 44 | auto next = swapPairs(head->next->next); 45 | auto curr = head->next; 46 | 47 | head->next = next; 48 | curr->next = head; 49 | head = curr; 50 | 51 | return head; 52 | } 53 | }; 54 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/December-2020/28. Reach a Number.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Reach a Number 3 | ============== 4 | 5 | You are standing at position 0 on an infinite number line. There is a goal at position target. 6 | 7 | On each move, you can either go left or right. During the n-th move (starting from 1), you take n steps. 8 | 9 | Return the minimum number of steps required to reach the destination. 10 | 11 | Example 1: 12 | Input: target = 3 13 | Output: 2 14 | Explanation: 15 | On the first move we step from 0 to 1. 16 | On the second step we step from 1 to 3. 17 | 18 | Example 2: 19 | Input: target = 2 20 | Output: 3 21 | Explanation: 22 | On the first move we step from 0 to 1. 23 | On the second move we step from 1 to -1. 24 | On the third move we step from -1 to 2. 25 | 26 | Note: 27 | target will be a non-zero integer in the range [-10^9, 10^9]. 28 | */ 29 | 30 | class Solution 31 | { 32 | public: 33 | int reachNumber(int target) 34 | { 35 | target = abs(target); 36 | long long n = ceil((-1.0 + sqrt(1 + 8.0 * target)) / 2); 37 | long long sum = n * (n + 1) / 2; 38 | if (sum == target) 39 | return n; 40 | long long res = sum - target; 41 | if ((res & 1) == 0) 42 | return n; 43 | else 44 | return n + ((n & 1) ? 2 : 1); 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/February-2021/07. Shortest Distance to a Character.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Shortest Distance to a Character 3 | ================================ 4 | 5 | Given a string s and a character c that occurs in s, return an array of integers answer where answer.length == s.length and answer[i] is the shortest distance from s[i] to the character c in s. 6 | 7 | Example 1 8 | Input: s = "loveleetcode", c = "e" 9 | Output: [3,2,1,0,1,0,0,1,2,2,1,0] 10 | 11 | Example 2: 12 | Input: s = "aaab", c = "b" 13 | Output: [3,2,1,0] 14 | 15 | Constraints: 16 | 1 <= s.length <= 104 17 | s[i] and c are lowercase English letters. 18 | c occurs at least once in s. 19 | */ 20 | 21 | class Solution 22 | { 23 | public: 24 | vector shortestToChar(string s, char c) 25 | { 26 | int n = s.size(); 27 | vector left(n), right(n); 28 | vector ans(n); 29 | 30 | int curr = INT_MAX; 31 | for (int i = 0; i < n; ++i) 32 | { 33 | if (s[i] == c) 34 | curr = i; 35 | left[i] = curr; 36 | } 37 | 38 | curr = INT_MAX; 39 | for (int i = n - 1; i >= 0; --i) 40 | { 41 | if (s[i] == c) 42 | curr = i; 43 | right[i] = curr; 44 | } 45 | 46 | for (int i = 0; i < n; ++i) 47 | { 48 | ans[i] = min(abs(i - left[i]), abs(i - right[i])); 49 | } 50 | return ans; 51 | } 52 | }; 53 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/February-2021/11. Valid Anagram.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Valid Anagram 3 | ============= 4 | 5 | Given two strings s and t , write a function to determine if t is an anagram of s. 6 | 7 | Example 1: 8 | Input: s = "anagram", t = "nagaram" 9 | Output: true 10 | 11 | Example 2: 12 | Input: s = "rat", t = "car" 13 | Output: false 14 | Note: 15 | You may assume the string contains only lowercase alphabets. 16 | 17 | Follow up: 18 | What if the inputs contain unicode characters? How would you adapt your solution to such case? 19 | */ 20 | 21 | class Solution 22 | { 23 | public: 24 | bool isAnagram(string s, string t) 25 | { 26 | vector c1(26, 0), c2(26, 0); 27 | for (auto &i : s) 28 | c1[i - 'a']++; 29 | for (auto &i : t) 30 | c2[i - 'a']++; 31 | for (int i = 0; i < 26; ++i) 32 | if (c1[i] != c2[i]) 33 | return false; 34 | return true; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/February-2021/21. Broken Calculator.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Broken Calculator 3 | ================= 4 | 5 | On a broken calculator that has a number showing on its display, we can perform two operations: 6 | 7 | Double: Multiply the number on the display by 2, or; 8 | Decrement: Subtract 1 from the number on the display. 9 | Initially, the calculator is displaying the number X. 10 | 11 | Return the minimum number of operations needed to display the number Y. 12 | 13 | Example 1: 14 | Input: X = 2, Y = 3 15 | Output: 2 16 | Explanation: Use double operation and then decrement operation {2 -> 4 -> 3}. 17 | 18 | Example 2: 19 | Input: X = 5, Y = 8 20 | Output: 2 21 | Explanation: Use decrement and then double {5 -> 4 -> 8}. 22 | 23 | Example 3: 24 | Input: X = 3, Y = 10 25 | Output: 3 26 | Explanation: Use double, decrement and double {3 -> 6 -> 5 -> 10}. 27 | 28 | Example 4: 29 | Input: X = 1024, Y = 1 30 | Output: 1023 31 | Explanation: Use decrement operations 1023 times. 32 | 33 | Note: 34 | 1 <= X <= 10^9 35 | 1 <= Y <= 10^9 36 | */ 37 | 38 | class Solution 39 | { 40 | public: 41 | int brokenCalc(int x, int y) 42 | { 43 | int count = 0; 44 | while (y != x) 45 | { 46 | if (x >= y) 47 | return ((x - y) + count); 48 | if (y % 2 == 0) 49 | y = y / 2; 50 | else 51 | y++; 52 | count++; 53 | } 54 | return count; 55 | } 56 | }; 57 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/February-2021/24. Score of Parentheses.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Score of Parentheses 3 | ==================== 4 | 5 | Given a balanced parentheses string S, compute the score of the string based on the following rule: 6 | 7 | () has score 1 8 | AB has score A + B, where A and B are balanced parentheses strings. 9 | (A) has score 2 * A, where A is a balanced parentheses string. 10 | 11 | Example 1: 12 | Input: "()" 13 | Output: 1 14 | 15 | Example 2: 16 | Input: "(())" 17 | Output: 2 18 | 19 | Example 3: 20 | Input: "()()" 21 | Output: 2 22 | 23 | Example 4: 24 | Input: "(()(()))" 25 | Output: 6 26 | 27 | Note: 28 | S is a balanced parentheses string, containing only ( and ). 29 | 2 <= S.length <= 50 30 | */ 31 | 32 | class Solution { 33 | public: 34 | int scoreOfParentheses(string S) { 35 | int ans = 0,count = 0, can_add = 0; 36 | 37 | for(int i=0; i &arr, int k) 33 | { 34 | long long curr = 1, count = 0; 35 | int i = 0; 36 | 37 | while (count < k) 38 | { 39 | if (i < arr.size()) 40 | { 41 | if (curr == arr[i]) 42 | { 43 | i++; 44 | } 45 | else 46 | count++; 47 | } 48 | else 49 | count++; 50 | curr++; 51 | } 52 | 53 | return curr - 1; 54 | } 55 | }; 56 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/January-2021/16. Kth Largest Element in an Array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Kth Largest Element in an Array 3 | ================================ 4 | 5 | Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. 6 | 7 | Example 1: 8 | Input: [3,2,1,5,6,4] and k = 2 9 | Output: 5 10 | 11 | Example 2: 12 | Input: [3,2,3,1,2,4,5,5,6] and k = 4 13 | Output: 4 14 | 15 | Note: 16 | You may assume k is always valid, 1 ≤ k ≤ array's length. 17 | */ 18 | 19 | class Solution 20 | { 21 | public: 22 | int findKthLargest(vector &nums, int k) 23 | { 24 | sort(nums.begin(), nums.end()); 25 | return nums[nums.size() - k]; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/January-2021/21. Find the Most Competitive Subsequence.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Find the Most Competitive Subsequence 3 | ===================================== 4 | 5 | Given an integer array nums and a positive integer k, return the most competitive subsequence of nums of size k. 6 | 7 | An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array. 8 | 9 | We define that a subsequence a is more competitive than a subsequence b (of the same length) if in the first position where a and b differ, subsequence a has a number less than the corresponding number in b. For example, [1,3,4] is more competitive than [1,3,5] because the first position they differ is at the final number, and 4 is less than 5. 10 | 11 | Example 1: 12 | Input: nums = [3,5,2,6], k = 2 13 | Output: [2,6] 14 | Explanation: Among the set of every possible subsequence: {[3,5], [3,2], [3,6], [5,2], [5,6], [2,6]}, [2,6] is the most competitive. 15 | 16 | Example 2: 17 | Input: nums = [2,4,3,3,5,4,9,6], k = 4 18 | Output: [2,3,3,4] 19 | 20 | Constraints: 21 | 1 <= nums.length <= 105 22 | 0 <= nums[i] <= 109 23 | 1 <= k <= nums.length 24 | 25 | Hint #1 26 | In lexicographical order, the elements to the left have higher priority than those that come after. Can you think of a strategy that incrementally builds the answer from left to right? 27 | */ -------------------------------------------------------------------------------- /Leetcode Daily Challenge/January-2021/25. 1's Are at Least Length K Places Away.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 1's Are at Least Length K Places Away 3 | ===================================== 4 | 5 | Given an array nums of 0s and 1s and an integer k, return True if all 1's are at least k places away from each other, otherwise return False. 6 | 7 | Example 1: 8 | Input: nums = [1,0,0,0,1,0,0,1], k = 2 9 | Output: true 10 | Explanation: Each of the 1s are at least 2 places away from each other. 11 | 12 | Example 2: 13 | Input: nums = [1,0,0,1,0,1], k = 2 14 | Output: false 15 | Explanation: The second 1 and third 1 are only one apart from each other. 16 | 17 | Example 3: 18 | Input: nums = [1,1,1,1,1], k = 0 19 | Output: true 20 | 21 | Example 4: 22 | Input: nums = [0,1,0,1], k = 1 23 | Output: true 24 | 25 | Constraints: 26 | 1 <= nums.length <= 105 27 | 0 <= k <= nums.length 28 | nums[i] is 0 or 1 29 | 30 | Hint #1 31 | Each time you find a number 1, check whether or not it is K or more places away from the next one. If it's not, return false. 32 | */ 33 | 34 | class Solution 35 | { 36 | public: 37 | bool kLengthApart(vector &nums, int k) 38 | { 39 | int c = k; 40 | for (int i = 0; i < nums.size(); ++i) 41 | { 42 | if (nums[i] == 1 && c < k) 43 | return false; 44 | if (nums[i] == 1 && c >= k) 45 | c = 0; 46 | else 47 | c++; 48 | } 49 | return true; 50 | } 51 | }; 52 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/January-2021/31. Next Permutation.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Next Permutation 3 | ================ 4 | 5 | Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. 6 | 7 | If such an arrangement is not possible, it must rearrange it as the lowest possible order (i.e., sorted in ascending order). 8 | 9 | The replacement must be in place and use only constant extra memory. 10 | 11 | Example 1: 12 | Input: nums = [1,2,3] 13 | Output: [1,3,2] 14 | 15 | Example 2: 16 | Input: nums = [3,2,1] 17 | Output: [1,2,3] 18 | 19 | Example 3: 20 | Input: nums = [1,1,5] 21 | Output: [1,5,1] 22 | 23 | Example 4: 24 | Input: nums = [1] 25 | Output: [1] 26 | 27 | Constraints: 28 | 1 <= nums.length <= 100 29 | 0 <= nums[i] <= 100 30 | */ 31 | 32 | class Solution 33 | { 34 | public: 35 | void nextPermutation(vector &nums) 36 | { 37 | int i = nums.size() - 2; 38 | while (i >= 0 && nums[i + 1] <= nums[i]) 39 | i--; 40 | 41 | if (i >= 0) 42 | { 43 | int j = nums.size() - 1; 44 | while (j >= 0 && nums[j] <= nums[i]) 45 | j--; 46 | swap(nums[i], nums[j]); 47 | } 48 | reverse(nums.begin() + i + 1, nums.end()); 49 | } 50 | }; -------------------------------------------------------------------------------- /Leetcode Daily Challenge/July-2021/02. Find K Closest Elements.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Find K Closest Elements 3 | ======================= 4 | 5 | Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order. 6 | 7 | An integer a is closer to x than an integer b if: 8 | 9 | |a - x| < |b - x|, or 10 | |a - x| == |b - x| and a < b 11 | 12 | Example 1: 13 | Input: arr = [1,2,3,4,5], k = 4, x = 3 14 | Output: [1,2,3,4] 15 | 16 | Example 2: 17 | Input: arr = [1,2,3,4,5], k = 4, x = -1 18 | Output: [1,2,3,4] 19 | 20 | Constraints: 21 | 1 <= k <= arr.length 22 | 1 <= arr.length <= 104 23 | arr is sorted in ascending order. 24 | -104 <= arr[i], x <= 104 25 | */ 26 | 27 | class Solution 28 | { 29 | public: 30 | vector findClosestElements(vector &arr, int k, int x) 31 | { 32 | sort(arr.begin(), arr.end(), [x](int &a, int &b) 33 | { 34 | if (abs(a - x) == abs(b - x)) 35 | return a < b; 36 | return abs(a - x) < abs(b - x); 37 | }); 38 | 39 | vector ans = vector(arr.begin(), arr.begin() + k); 40 | sort(ans.begin(), ans.end()); 41 | return ans; 42 | } 43 | }; -------------------------------------------------------------------------------- /Leetcode Daily Challenge/July-2021/15. Valid Triangle Number.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Valid Triangle Number 3 | ===================== 4 | 5 | Given an integer array nums, return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle. 6 | 7 | Example 1: 8 | Input: nums = [2,2,3,4] 9 | Output: 3 10 | Explanation: Valid combinations are: 11 | 2,3,4 (using the first 2) 12 | 2,3,4 (using the second 2) 13 | 2,2,3 14 | 15 | Example 2: 16 | Input: nums = [4,2,3,4] 17 | Output: 4 18 | 19 | Constraints: 20 | 1 <= nums.length <= 1000 21 | 0 <= nums[i] <= 1000 22 | */ 23 | 24 | class Solution 25 | { 26 | public: 27 | int triangleNumber(vector &A) 28 | { 29 | sort(A.begin(), A.end()); 30 | int ans = 0; 31 | 32 | for (int i = 0; i < A.size(); ++i) 33 | { 34 | for (int j = i + 1; j < A.size(); ++j) 35 | { 36 | int sum = A[i] + A[j]; 37 | auto it = lower_bound(A.begin() + j + 1, A.end(), sum) - A.begin(); 38 | it--; 39 | ans += (it - j); 40 | } 41 | } 42 | 43 | return ans; 44 | } 45 | }; -------------------------------------------------------------------------------- /Leetcode Daily Challenge/July-2021/27. 3Sum Closest.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3Sum Closest 3 | ============ 4 | 5 | Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution. 6 | 7 | Example 1: 8 | Input: nums = [-1,2,1,-4], target = 1 9 | Output: 2 10 | Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). 11 | 12 | Constraints: 13 | 3 <= nums.length <= 10^3 14 | -10^3 <= nums[i] <= 10^3 15 | -10^4 <= target <= 10^4 16 | */ 17 | 18 | class Solution { 19 | public: 20 | int threeSumClosest(vector& nums, int target) { 21 | int ans = INT_MIN, diff = INT_MAX; 22 | sort(nums.begin(), nums.end()); 23 | 24 | for(int i = 0; i < nums.size(); ++i) { 25 | int j = i+1, k = nums.size()-1; 26 | while(j < k) { 27 | int val = nums[i] + nums[j] + nums[k]; 28 | if(abs(target - val) < diff) { 29 | ans = val; 30 | diff = abs(target - val); 31 | } 32 | 33 | if(val < target) j++; 34 | else k--; 35 | } 36 | } 37 | 38 | return ans; 39 | } 40 | }; -------------------------------------------------------------------------------- /Leetcode Daily Challenge/July-2021/31. Trapping Rain Water.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Trapping Rain Water 3 | =================== 4 | 5 | Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining. 6 | 7 | Example 1: 8 | Input: height = [0,1,0,2,1,0,1,3,2,1,2,1] 9 | Output: 6 10 | Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. 11 | 12 | Example 2: 13 | Input: height = [4,2,0,3,2,5] 14 | Output: 9 15 | 16 | Constraints: 17 | n == height.length 18 | 0 <= n <= 3 * 104 19 | 0 <= height[i] <= 105 20 | */ 21 | 22 | class Solution 23 | { 24 | public: 25 | int trap(vector &height) 26 | { 27 | int n = height.size(); 28 | 29 | if (n <= 1) 30 | return 0; 31 | 32 | vector left(n, 0), right(n, 0); 33 | 34 | left[0] = height[0]; 35 | right[n - 1] = height[n - 1]; 36 | 37 | int ans = 0; 38 | for (int i = 1; i < n; ++i) 39 | left[i] = max(left[i - 1], height[i]); 40 | for (int i = n - 2; i >= 0; --i) 41 | right[i] = max(right[i + 1], height[i]); 42 | 43 | for (int i = 1; i < n - 1; ++i) 44 | { 45 | int val = min(left[i], right[i]) - height[i]; 46 | ans += val; 47 | } 48 | 49 | return ans; 50 | } 51 | }; -------------------------------------------------------------------------------- /Leetcode Daily Challenge/June-2021/06. Longest Consecutive Sequence.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Longest Consecutive Sequence 3 | ============================ 4 | 5 | Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. 6 | 7 | You must write an algorithm that runs in O(n) time. 8 | 9 | Example 1: 10 | Input: nums = [100,4,200,1,3,2] 11 | Output: 4 12 | Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4. 13 | 14 | Example 2: 15 | Input: nums = [0,3,7,2,5,8,4,6,0,1] 16 | Output: 9 17 | 18 | Constraints: 19 | 0 <= nums.length <= 105 20 | -109 <= nums[i] <= 109 21 | */ 22 | 23 | class Solution 24 | { 25 | public: 26 | int longestConsecutive(vector &nums) 27 | { 28 | int n = nums.size(), ans = 0; 29 | unordered_set vis; 30 | for (auto &i : nums) 31 | vis.insert(i); 32 | 33 | for (auto i : nums) 34 | { 35 | if (vis.count(i - 1)) 36 | continue; 37 | else 38 | { 39 | int count = 0; 40 | while (vis.count(i)) 41 | { 42 | count++; 43 | i++; 44 | } 45 | ans = max(ans, count); 46 | } 47 | } 48 | 49 | return ans; 50 | } 51 | }; 52 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/June-2021/07. Min Cost Climbing Stairs.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Min Cost Climbing Stairs 3 | ======================== 4 | 5 | You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps. 6 | 7 | You can either start from the step with index 0, or the step with index 1. 8 | 9 | Return the minimum cost to reach the top of the floor. 10 | 11 | Example 1: 12 | Input: cost = [10,15,20] 13 | Output: 15 14 | Explanation: Cheapest is: start on cost[1], pay that cost, and go to the top. 15 | 16 | Example 2: 17 | Input: cost = [1,100,1,1,1,100,1,1,100,1] 18 | Output: 6 19 | Explanation: Cheapest is: start on cost[0], and only step on 1s, skipping cost[3]. 20 | 21 | Constraints: 22 | 2 <= cost.length <= 1000 23 | 0 <= cost[i] <= 999 24 | 25 | Hint #1 26 | Say f[i] is the final cost to climb to the top from step i. Then f[i] = cost[i] + min(f[i+1], f[i+2]). 27 | */ 28 | 29 | class Solution 30 | { 31 | public: 32 | int minCostClimbingStairs(vector &cost) 33 | { 34 | int n = cost.size(); 35 | vector dp(n + 1, INT_MAX); 36 | dp[0] = cost[0]; 37 | dp[1] = cost[1]; 38 | 39 | for (int i = 2; i <= n; ++i) 40 | { 41 | dp[i] = min(dp[i - 1], dp[i - 2]); 42 | if (i != n) 43 | dp[i] += cost[i]; 44 | } 45 | 46 | return dp[n]; 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/June-2021/16. Generate Parentheses.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Generate Parentheses 3 | ==================== 4 | 5 | Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 6 | 7 | Example 1: 8 | Input: n = 3 9 | Output: ["((()))","(()())","(())()","()(())","()()()"] 10 | 11 | Example 2: 12 | Input: n = 1 13 | Output: ["()"] 14 | 15 | Constraints: 16 | 1 <= n <= 8 17 | */ 18 | 19 | class Solution 20 | { 21 | public: 22 | void dfs(int n, int o, int c, vector &ans, string stn) 23 | { 24 | if (o == n && c == n) 25 | { 26 | ans.push_back(stn); 27 | return; 28 | } 29 | 30 | if (o < n) 31 | dfs(n, o + 1, c, ans, stn + "("); 32 | if (c < o) 33 | dfs(n, o, c + 1, ans, stn + ")"); 34 | } 35 | 36 | vector generateParenthesis(int n) 37 | { 38 | vector ans; 39 | dfs(n, 0, 0, ans, ""); 40 | return ans; 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/June-2021/17. Number of Subarrays with Bounded Maximum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Number of Subarrays with Bounded Maximum 3 | ========================================= 4 | 5 | We are given an array nums of positive integers, and two positive integers left and right (left <= right). 6 | 7 | Return the number of (contiguous, non-empty) subarrays such that the value of the maximum array element in that subarray is at least left and at most right. 8 | 9 | Example: 10 | Input: 11 | nums = [2, 1, 4, 3] 12 | left = 2 13 | right = 3 14 | Output: 3 15 | Explanation: There are three subarrays that meet the requirements: [2], [2, 1], [3]. 16 | Note: 17 | 18 | left, right, and nums[i] will be an integer in the range [0, 109]. 19 | The length of nums will be in the range of [1, 50000]. 20 | */ 21 | 22 | class Solution 23 | { 24 | public: 25 | int numSubarrayBoundedMax(vector &nums, int left, int right) 26 | { 27 | int ans = 0; 28 | int i = 0, j = 0, count = 0; 29 | 30 | while (j < nums.size()) 31 | { 32 | if (nums[j] >= left && nums[j] <= right) 33 | { 34 | count = (j - i + 1); 35 | ans += count; 36 | } 37 | else if (nums[j] < left) 38 | ans += count; 39 | else 40 | { 41 | i = j + 1; 42 | count = 0; 43 | } 44 | j++; 45 | } 46 | return ans; 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/June-2021/21. Pascal's Triangle.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Pascal's Triangle 3 | ================= 4 | 5 | Given an integer numRows, return the first numRows of Pascal's triangle. 6 | 7 | In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: 8 | 9 | Example 1: 10 | Input: numRows = 5 11 | Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] 12 | 13 | Example 2: 14 | Input: numRows = 1 15 | Output: [[1]] 16 | 17 | Constraints: 18 | 1 <= numRows <= 30 19 | */ 20 | 21 | class Solution 22 | { 23 | public: 24 | vector> generate(int n) 25 | { 26 | if (n == 1) 27 | return {{1}}; 28 | if (n == 2) 29 | return {{1}, {1, 1}}; 30 | 31 | vector> ans = {{1}, {1, 1}}; 32 | 33 | for (int i = 3; i <= n; ++i) 34 | { 35 | vector temp(i, 0); 36 | temp[0] = 1; 37 | temp[i - 1] = 1; 38 | 39 | for (int j = 1; j < i - 1; ++j) 40 | temp[j] = ans[i - 2][j - 1] + ans[i - 2][j]; 41 | 42 | ans.push_back(temp); 43 | } 44 | 45 | return ans; 46 | } 47 | }; 48 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/March-2021/02. Set Mismatch.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Set Mismatch 3 | ============ 4 | 5 | You have a set of integers s, which originally contains all the numbers from 1 to n. Unfortunately, due to some error, one of the numbers in s got duplicated to another number in the set, which results in repetition of one number and loss of another number. 6 | 7 | You are given an integer array nums representing the data status of this set after the error. 8 | 9 | Find the number that occurs twice and the number that is missing and return them in the form of an array. 10 | 11 | Example 1: 12 | Input: nums = [1,2,2,4] 13 | Output: [2,3] 14 | 15 | Example 2: 16 | Input: nums = [1,1] 17 | Output: [1,2] 18 | 19 | Constraints: 20 | 2 <= nums.length <= 104 21 | 1 <= nums[i] <= 104 22 | */ 23 | 24 | class Solution 25 | { 26 | public: 27 | vector findErrorNums(vector &nums) 28 | { 29 | unordered_map freq; 30 | vector ans; 31 | 32 | for (auto &i : nums) 33 | freq[i]++; 34 | for (auto &i : freq) 35 | if (i.second == 2) 36 | ans.push_back(i.first); 37 | for (auto i = 1; i <= nums.size(); ++i) 38 | if (freq[i] == 0) 39 | ans.push_back(i); 40 | 41 | return ans; 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/March-2021/11. Coin Change.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Coin Change 3 | =========== 4 | 5 | You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. 6 | 7 | You may assume that you have an infinite number of each kind of coin. 8 | 9 | Example 1: 10 | Input: coins = [1,2,5], amount = 11 11 | Output: 3 12 | Explanation: 11 = 5 + 5 + 1 13 | 14 | Example 2: 15 | Input: coins = [2], amount = 3 16 | Output: -1 17 | 18 | Example 3: 19 | Input: coins = [1], amount = 0 20 | Output: 0 21 | 22 | Example 4: 23 | Input: coins = [1], amount = 1 24 | Output: 1 25 | 26 | Example 5: 27 | Input: coins = [1], amount = 2 28 | Output: 2 29 | 30 | Constraints: 31 | 1 <= coins.length <= 12 32 | 1 <= coins[i] <= 231 - 1 33 | 0 <= amount <= 104 34 | */ 35 | 36 | class Solution { 37 | public: 38 | int coinChange(vector& coins, int amount) { 39 | vector dp(amount+1, INT_MAX); 40 | dp[0] = 0; 41 | 42 | for(int i=1; i<=amount; ++i){ 43 | for(auto &coin: coins){ 44 | if(coin <= i) dp[i] = min(dp[i], dp[i-coin]+1); 45 | } 46 | } 47 | 48 | return dp[amount] == INT_MAX ? -1 : dp[amount]; 49 | } 50 | }; 51 | 52 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/March-2021/15. Encode and Decode TinyURL.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Encode and Decode TinyURL 3 | ========================= 4 | 5 | Note: This is a companion problem to the System Design problem: Design TinyURL. 6 | 7 | TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk. 8 | 9 | Design the encode and decode methods for the TinyURL service. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL. 10 | */ 11 | 12 | class Solution 13 | { 14 | public: 15 | vector arr; 16 | // Encodes a URL to a shortened URL. 17 | string encode(string longUrl) 18 | { 19 | arr.push_back(longUrl); 20 | int size = arr.size(); 21 | string ans = "http://tinyurl.com/" + to_string(size); 22 | return ans; 23 | } 24 | 25 | // Decodes a shortened URL to its original URL. 26 | string decode(string shortUrl) 27 | { 28 | string str = shortUrl.substr(19); 29 | return arr[stoi(str) - 1]; 30 | } 31 | }; 32 | 33 | // Your Solution object will be instantiated and called as such: 34 | // Solution solution; 35 | // solution.decode(solution.encode(url)); 36 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/March-2021/21. Reordered Power of 2.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Reordered Power of 2 3 | ==================== 4 | 5 | Starting with a positive integer N, we reorder the digits in any order (including the original order) such that the leading digit is not zero. 6 | 7 | Return true if and only if we can do this in a way such that the resulting number is a power of 2. 8 | 9 | Example 1: 10 | Input: 1 11 | Output: true 12 | 13 | Example 2: 14 | Input: 10 15 | Output: false 16 | 17 | Example 3: 18 | Input: 16 19 | Output: true 20 | 21 | Example 4: 22 | Input: 24 23 | Output: false 24 | 25 | Example 5: 26 | Input: 46 27 | Output: true 28 | 29 | Note: 30 | 1 <= N <= 10^9 31 | */ 32 | 33 | class Solution 34 | { 35 | public: 36 | bool reorderedPowerOf2(int N) 37 | { 38 | string st = to_string(N); 39 | sort(st.begin(), st.end()); 40 | do 41 | { 42 | if (st[0] != '0') 43 | { 44 | int num = stoi(st); 45 | if ((int)log2(num) == (double)log2(num)) 46 | return true; 47 | } 48 | } while (next_permutation(st.begin(), st.end())); 49 | return false; 50 | } 51 | }; 52 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/March-2021/24. Advantage Shuffle.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Advantage Shuffle 3 | ================= 4 | 5 | Given two arrays A and B of equal size, the advantage of A with respect to B is the number of indices i for which A[i] > B[i]. 6 | 7 | Return any permutation of A that maximizes its advantage with respect to B. 8 | 9 | Example 1: 10 | Input: A = [2,7,11,15], B = [1,10,4,11] 11 | Output: [2,11,7,15] 12 | 13 | Example 2: 14 | Input: A = [12,24,8,32], B = [13,25,32,11] 15 | Output: [24,32,8,12] 16 | 17 | Note: 18 | 1 <= A.length = B.length <= 10000 19 | 0 <= A[i] <= 10^9 20 | 0 <= B[i] <= 10^9 21 | */ 22 | 23 | class Solution 24 | { 25 | public: 26 | vector advantageCount(vector &A, vector &B) 27 | { 28 | vector> b; 29 | for (int i = 0; i < B.size(); ++i) 30 | b.push_back({B[i], i}); 31 | sort(b.begin(), b.end(), greater>()); 32 | sort(A.begin(), A.end()); 33 | int i = 0, j = A.size() - 1; 34 | vector ans(A.size(), -1); 35 | 36 | for (int k = 0; k < b.size(); ++k) 37 | { 38 | int pos = b[k][1]; 39 | 40 | if (A[j] > b[k][0]) 41 | { 42 | ans[pos] = A[j]; 43 | j--; 44 | } 45 | else 46 | { 47 | ans[pos] = A[i]; 48 | i++; 49 | } 50 | } 51 | 52 | return ans; 53 | } 54 | }; 55 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/May-2021/03. Running Sum of 1d Array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Running Sum of 1d Array 3 | ======================= 4 | 5 | Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]). 6 | 7 | Return the running sum of nums. 8 | 9 | Example 1: 10 | Input: nums = [1,2,3,4] 11 | Output: [1,3,6,10] 12 | Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4]. 13 | 14 | Example 2: 15 | Input: nums = [1,1,1,1,1] 16 | Output: [1,2,3,4,5] 17 | Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1]. 18 | 19 | Example 3: 20 | Input: nums = [3,1,2,10,1] 21 | Output: [3,4,6,16,17] 22 | 23 | Constraints: 24 | 1 <= nums.length <= 1000 25 | -10^6 <= nums[i] <= 10^6 26 | 27 | Hint #1 28 | Think about how we can calculate the i-th number in the running sum from the (i-1)-th number. 29 | */ 30 | 31 | class Solution 32 | { 33 | public: 34 | vector runningSum(vector &nums) 35 | { 36 | for (int i = 1; i < nums.size(); ++i) 37 | { 38 | nums[i] += nums[i - 1]; 39 | } 40 | return nums; 41 | } 42 | }; -------------------------------------------------------------------------------- /Leetcode Daily Challenge/May-2021/04. Non-decreasing Array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Non-decreasing Array 3 | ==================== 4 | 5 | Given an array nums with n integers, your task is to check if it could become non-decreasing by modifying at most one element. 6 | 7 | We define an array is non-decreasing if nums[i] <= nums[i + 1] holds for every i (0-based) such that (0 <= i <= n - 2). 8 | 9 | Example 1: 10 | Input: nums = [4,2,3] 11 | Output: true 12 | Explanation: You could modify the first 4 to 1 to get a non-decreasing array. 13 | 14 | Example 2: 15 | Input: nums = [4,2,1] 16 | Output: false 17 | Explanation: You can't get a non-decreasing array by modify at most one element. 18 | 19 | Constraints: 20 | n == nums.length 21 | 1 <= n <= 104 22 | -105 <= nums[i] <= 105 23 | */ 24 | 25 | class Solution 26 | { 27 | public: 28 | bool checkPossibility(vector &nums) 29 | { 30 | int count = 0; 31 | for (int i = 1; i < nums.size(); ++i) 32 | { 33 | if (nums[i - 1] > nums[i]) 34 | { 35 | if (i - 2 < 0 || nums[i - 2] <= nums[i]) 36 | nums[i - 1] = nums[i]; 37 | else 38 | nums[i] = nums[i - 1]; 39 | count++; 40 | } 41 | } 42 | return count <= 1; 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/May-2021/05. Jump Game II.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Jump Game II 3 | ============ 4 | 5 | Given an array of non-negative integers nums, you are initially positioned at the first index of the array. 6 | 7 | Each element in the array represents your maximum jump length at that position. 8 | 9 | Your goal is to reach the last index in the minimum number of jumps. 10 | 11 | You can assume that you can always reach the last index. 12 | 13 | Example 1: 14 | Input: nums = [2,3,1,1,4] 15 | Output: 2 16 | Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index. 17 | 18 | Example 2: 19 | Input: nums = [2,3,0,1,4] 20 | Output: 2 21 | 22 | Constraints: 23 | 1 <= nums.length <= 1000 24 | 0 <= nums[i] <= 105 25 | */ 26 | 27 | class Solution 28 | { 29 | public: 30 | int jump(vector &nums) 31 | { 32 | int n = nums.size(); 33 | vector dp(n, INT_MAX); 34 | dp[0] = 0; 35 | for (int i = 0; i < nums.size() - 1; ++i) 36 | { 37 | if (nums[i] == 0 || dp[i] == INT_MAX) 38 | continue; 39 | for (int j = 1; j <= nums[i] && i + j < n; ++j) 40 | { 41 | dp[i + j] = min(dp[i + j], 1 + dp[i]); 42 | } 43 | } 44 | return dp[n - 1]; 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/May-2021/07. Delete Operation for Two Strings.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Delete Operation for Two Strings 3 | ================================ 4 | 5 | Given two strings word1 and word2, return the minimum number of steps required to make word1 and word2 the same. 6 | 7 | In one step, you can delete exactly one character in either string. 8 | 9 | Example 1: 10 | Input: word1 = "sea", word2 = "eat" 11 | Output: 2 12 | Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea". 13 | 14 | Example 2: 15 | Input: word1 = "leetcode", word2 = "etco" 16 | Output: 4 17 | 18 | Constraints: 19 | 1 <= word1.length, word2.length <= 500 20 | word1 and word2 consist of only lowercase English letters. 21 | */ 22 | 23 | class Solution 24 | { 25 | public: 26 | int minDistance(string A, string B) 27 | { 28 | vector> dp(A.size() + 1, vector(B.size() + 1, 0)); 29 | for (int i = 1; i <= A.size(); ++i) 30 | { 31 | for (int j = 1; j <= B.size(); ++j) 32 | { 33 | if (A[i - 1] == B[j - 1]) 34 | dp[i][j] = 1 + dp[i - 1][j - 1]; 35 | else 36 | dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]); 37 | } 38 | } 39 | 40 | return A.size() + B.size() - 2 * dp[A.size()][B.size()]; 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/May-2021/19. Minimum Moves to Equal Array Elements II.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Minimum Moves to Equal Array Elements II 3 | ======================================== 4 | 5 | Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal. 6 | 7 | In one move, you can increment or decrement an element of the array by 1. 8 | 9 | Example 1: 10 | Input: nums = [1,2,3] 11 | Output: 2 12 | Explanation: 13 | Only two moves are needed (remember each move increments or decrements one element): 14 | [1,2,3] => [2,2,3] => [2,2,2] 15 | 16 | Example 2: 17 | Input: nums = [1,10,2,9] 18 | Output: 16 19 | 20 | Constraints: 21 | n == nums.length 22 | 1 <= nums.length <= 105 23 | -109 <= nums[i] <= 109 24 | */ 25 | 26 | class Solution 27 | { 28 | public: 29 | int minMoves2(vector &nums) 30 | { 31 | sort(nums.begin(), nums.end()); 32 | int tar = nums[nums.size() / 2]; 33 | 34 | int ans = 0; 35 | for (auto &i : nums) 36 | { 37 | ans += abs(i - tar); 38 | } 39 | return ans; 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/May-2021/24. To Lower Case.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | To Lower Case 3 | ============= 4 | 5 | Given a string s, return the string after replacing every uppercase letter with the same lowercase letter. 6 | 7 | Example 1: 8 | Input: s = "Hello" 9 | Output: "hello" 10 | 11 | Example 2: 12 | Input: s = "here" 13 | Output: "here" 14 | 15 | Example 3: 16 | Input: s = "LOVELY" 17 | Output: "lovely" 18 | 19 | Constraints: 20 | 1 <= s.length <= 100 21 | s consists of printable ASCII characters. 22 | 23 | Hint #1 24 | Most languages support lowercase conversion for a string data type. However, that is certainly not the purpose of the problem. Think about how the implementation of the lowercase function call can be done easily. 25 | 26 | Hint #2 27 | Think ASCII! 28 | 29 | Hint #3 30 | Think about the different capital letters and their ASCII codes and how that relates to their lowercase counterparts. Does there seem to be any pattern there? Any mathematical relationship that we can use? 31 | */ 32 | 33 | class Solution 34 | { 35 | public: 36 | string toLowerCase(string s) 37 | { 38 | for (auto &i : s) 39 | { 40 | if (i >= 'A' && i <= 'Z') 41 | i = i - 'A' + 'a'; 42 | } 43 | return s; 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/May-2021/30. Maximum Gap.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Maximum Gap 3 | =========== 4 | 5 | Given an integer array nums, return the maximum difference between two successive elements in its sorted form. If the array contains less than two elements, return 0. 6 | 7 | You must write an algorithm that runs in linear time and uses linear extra space. 8 | 9 | Example 1: 10 | Input: nums = [3,6,9,1] 11 | Output: 3 12 | Explanation: The sorted form of the array is [1,3,6,9], either (3,6) or (6,9) has the maximum difference 3. 13 | 14 | Example 2: 15 | Input: nums = [10] 16 | Output: 0 17 | Explanation: The array contains less than 2 elements, therefore return 0. 18 | 19 | Constraints: 20 | 1 <= nums.length <= 104 21 | 0 <= nums[i] <= 109 22 | 23 | */ 24 | 25 | class Solution 26 | { 27 | public: 28 | int maximumGap(vector &nums) 29 | { 30 | if (nums.size() < 2) 31 | return 0; 32 | sort(nums.begin(), nums.end()); 33 | int ans = nums[1] - nums[0]; 34 | for (int i = 0; i < nums.size() - 1; ++i) 35 | { 36 | ans = max(ans, nums[i + 1] - nums[i]); 37 | } 38 | return ans; 39 | } 40 | }; -------------------------------------------------------------------------------- /Leetcode Daily Challenge/November-2020/12. Permutations II.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Permutations II 3 | =============== 4 | 5 | Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order. 6 | 7 | 8 | 9 | Example 1: 10 | Input: nums = [1,1,2] 11 | Output: 12 | [[1,1,2], 13 | [1,2,1], 14 | [2,1,1]] 15 | 16 | Example 2: 17 | Input: nums = [1,2,3] 18 | Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] 19 | 20 | 21 | Constraints: 22 | 1 <= nums.length <= 8 23 | -10 <= nums[i] <= 10 24 | */ 25 | 26 | class Solution 27 | { 28 | public: 29 | vector> permuteUnique(vector &nums) 30 | { 31 | sort(nums.begin(), nums.end()); 32 | vector> ans; 33 | do 34 | { 35 | ans.push_back(nums); 36 | } while (next_permutation(nums.begin(), nums.end())); 37 | return ans; 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/November-2020/17. Mirror Reflection.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Mirror Reflection 3 | ================= 4 | 5 | There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0, 1, and 2. 6 | 7 | The square room has walls of length p, and a laser ray from the southwest corner first meets the east wall at a distance q from the 0th receptor. 8 | 9 | Return the number of the receptor that the ray meets first. (It is guaranteed that the ray will meet a receptor eventually.) 10 | 11 | 12 | Example 1: 13 | Input: p = 2, q = 1 14 | Output: 2 15 | Explanation: The ray meets receptor 2 the first time it gets reflected back to the left wall. 16 | 17 | Note: 18 | 1 <= p <= 1000 19 | 0 <= q <= p 20 | */ 21 | 22 | class Solution 23 | { 24 | public: 25 | int mirrorReflection(int p, int q) 26 | { 27 | while (p % 2 == 0 && q % 2 == 0) 28 | { 29 | p /= 2; 30 | q /= 2; 31 | } 32 | 33 | if (p % 2 == 0) 34 | return 2; 35 | if (q % 2 != 0) 36 | return 1; 37 | return 0; 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/November-2020/20. Search in Rotated Sorted Array II.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Search in Rotated Sorted Array II 3 | ================================= 4 | 5 | Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. 6 | (i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]). 7 | You are given a target value to search. If found in the array return true, otherwise return false. 8 | 9 | Example 1: 10 | Input: nums = [2,5,6,0,0,1,2], target = 0 11 | Output: true 12 | 13 | Example 2: 14 | Input: nums = [2,5,6,0,0,1,2], target = 3 15 | Output: false 16 | 17 | Follow up: 18 | This is a follow up problem to Search in Rotated Sorted Array, where nums may contain duplicates. 19 | Would this affect the run-time complexity? How and why? 20 | */ 21 | 22 | class Solution 23 | { 24 | public: 25 | bool search(vector &nums, int target) 26 | { 27 | for (auto &i : nums) 28 | if (i == target) 29 | return true; 30 | return false; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/November-2020/25. Smallest Integer Divisible by K.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Smallest Integer Divisible by K 3 | =============================== 4 | 5 | Given a positive integer K, you need to find the length of the smallest positive integer N such that N is divisible by K, and N only contains the digit 1. 6 | 7 | Return the length of N. If there is no such N, return -1. 8 | Note: N may not fit in a 64-bit signed integer. 9 | 10 | 11 | Example 1: 12 | Input: K = 1 13 | Output: 1 14 | Explanation: The smallest answer is N = 1, which has length 1. 15 | 16 | Example 2: 17 | Input: K = 2 18 | Output: -1 19 | Explanation: There is no such positive integer N divisible by 2. 20 | 21 | Example 3: 22 | Input: K = 3 23 | Output: 3 24 | Explanation: The smallest answer is N = 111, which has length 3. 25 | 26 | 27 | Constraints: 28 | 1 <= K <= 105 29 | 30 | Hint #1 31 | 11111 = 1111 * 10 + 1 We only need to store remainders modulo K. 32 | 33 | Hint #2 34 | If we never get a remainder of 0, why would that happen, and how would we know that? 35 | */ 36 | 37 | class Solution 38 | { 39 | public: 40 | int smallestRepunitDivByK(int K) 41 | { 42 | int rem = 0; 43 | for (int l = 1; l <= K; l++) 44 | { 45 | rem = (rem * 10 + 1) % K; 46 | if (rem == 0) 47 | return l; 48 | } 49 | return -1; 50 | } 51 | }; 52 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/October-2020/02. Combination Sum.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> combinationSum(int[] can, int tar) { 3 | List> ans = new ArrayList<>(); 4 | List temp = new ArrayList<>(); 5 | some(0, can, tar, ans, temp, 0); 6 | return ans; 7 | } 8 | 9 | public static void some(int i, int[] can, int tar, List> ans, List temp, int sum) { 10 | if (sum == tar) { 11 | ans.add(new ArrayList<>(temp)); 12 | return; 13 | } 14 | if (i >= can.length) { 15 | return; 16 | } 17 | if (sum > tar) 18 | return; 19 | 20 | temp.add(can[i]); 21 | some(i, can, tar, ans, temp, sum + can[i]); 22 | temp.remove(temp.size() - 1); 23 | some(i + 1, can, tar, ans, temp, sum); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/October-2020/08. Binary Search.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Binary Search 3 | ============= 4 | 5 | Given a sorted (in ascending order) integer array nums of n elements and a target value, write a function to search target in nums. If target exists, then return its index, otherwise return -1. 6 | 7 | 8 | Example 1: 9 | Input: nums = [-1,0,3,5,9,12], target = 9 10 | Output: 4 11 | Explanation: 9 exists in nums and its index is 4 12 | 13 | Example 2: 14 | Input: nums = [-1,0,3,5,9,12], target = 2 15 | Output: -1 16 | Explanation: 2 does not exist in nums so return -1 17 | 18 | 19 | Note: 20 | You may assume that all elements in nums are unique. 21 | n will be in the range [1, 10000]. 22 | The value of each element in nums will be in the range [-9999, 9999]. 23 | */ 24 | 25 | class Solution { 26 | public: 27 | int search(vector& nums, int target) { 28 | int f=0, b=nums.size()-1; 29 | while(f<=b){ 30 | int mid = (f+b)/2; 31 | if(nums[mid]==target) return mid; 32 | else if(nums[mid]>target) b=mid-1; 33 | else f=mid+1; 34 | } 35 | return -1; 36 | } 37 | }; -------------------------------------------------------------------------------- /Leetcode Daily Challenge/October-2020/08. Binary Search.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int search(int[] nums, int target) { 3 | int low=0; 4 | int high=nums.length-1; 5 | 6 | while(low<=high){ 7 | int m=(low+high)/2; 8 | if(target> &matrix, int target) 36 | { 37 | if (matrix.size() == 0) 38 | return false; 39 | int m = matrix.size(), n = matrix[0].size(); 40 | int r = 0, c = n - 1; 41 | 42 | while (r < m && c >= 0) 43 | { 44 | if (matrix[r][c] == target) 45 | return true; 46 | else if (matrix[r][c] < target) 47 | r++; 48 | else 49 | c--; 50 | } 51 | 52 | return false; 53 | } 54 | }; 55 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/October-2020/17. Repeated DNA Sequences.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Repeated DNA Sequences 3 | ====================== 4 | 5 | All DNA is composed of a series of nucleotides abbreviated as 'A', 'C', 'G', and 'T', for example: "ACGAATTCCG". When studying DNA, it is sometimes useful to identify repeated sequences within the DNA. 6 | 7 | Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. 8 | 9 | 10 | Example 1: 11 | Input: s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT" 12 | Output: ["AAAAACCCCC","CCCCCAAAAA"] 13 | 14 | Example 2: 15 | Input: s = "AAAAAAAAAAAAA" 16 | Output: ["AAAAAAAAAA"] 17 | 18 | Constraints: 19 | 20 | 0 <= s.length <= 105 21 | s[i] is 'A', 'C', 'G', or 'T'. 22 | 23 | */ 24 | 25 | class Solution 26 | { 27 | public: 28 | vector findRepeatedDnaSequences(string s) 29 | { 30 | if (s.size() < 10) 31 | return {}; 32 | unordered_map m; 33 | vector ans; 34 | 35 | for (int i = 0; i <= s.size() - 10; ++i) 36 | { 37 | string subStr = s.substr(i, 10); 38 | m[subStr]++; 39 | } 40 | 41 | for (auto it = m.begin(); it != m.end(); ++it) 42 | { 43 | cout << it->first << " " << it->second << endl; 44 | if (it->second > 1) 45 | ans.push_back(it->first); 46 | } 47 | 48 | return ans; 49 | } 50 | }; 51 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/October-2021/10. Bitwise AND of Numbers Range.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive. 3 | 4 | 5 | Example 1: 6 | 7 | Input: left = 5, right = 7 8 | Output: 4 9 | 10 | 11 | Example 2: 12 | 13 | Input: left = 0, right = 0 14 | Output: 0 15 | 16 | 17 | Example 3: 18 | 19 | Input: left = 1, right = 2147483647 20 | Output: 0 21 | 22 | 23 | Constraints: 24 | 25 | 0 <= left <= right <= 231 - 1 26 | */ 27 | 28 | class Solution { 29 | public: 30 | int pos(int x) { 31 | int cnt = -1; 32 | 33 | while(x) { 34 | x>>=1; 35 | cnt++; 36 | } 37 | 38 | return cnt; 39 | } 40 | 41 | int rangeBitwiseAnd(int l, int r) { 42 | int res = 0; 43 | 44 | while(l&&r) { 45 | int p1 = pos(l); 46 | int p2 = pos(r); 47 | 48 | if(p1!=p2) 49 | break; 50 | 51 | int val = (int)pow(2,p1); 52 | res+=val; 53 | 54 | l = l-val; 55 | r = r-val; 56 | } 57 | 58 | return res; 59 | } 60 | }; -------------------------------------------------------------------------------- /Leetcode Daily Challenge/October-2021/14. Perfect Squares.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer n, return the least number of perfect square numbers that sum to n. 3 | 4 | A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: n = 12 11 | Output: 3 12 | Explanation: 12 = 4 + 4 + 4. 13 | 14 | 15 | Example 2: 16 | 17 | Input: n = 13 18 | Output: 2 19 | Explanation: 13 = 4 + 9. 20 | 21 | 22 | Constraints: 23 | 24 | 1 <= n <= 104 25 | */ 26 | 27 | class Solution { 28 | public: 29 | int numSquares(int n) { 30 | vector count(n+1,INT_MAX); 31 | 32 | count[0]=0; 33 | for(int i=1;i<=n;i++) { 34 | for(int j=1;j*j<=i;j++) { 35 | count[i]=min(count[i],count[i-j*j]+1); 36 | } 37 | } 38 | 39 | return count[n]; 40 | 41 | 42 | } 43 | }; -------------------------------------------------------------------------------- /Leetcode Daily Challenge/October-2021/3. Jump Game.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | #Hacktoberfest2021 3 | You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position. 4 | 5 | Return true if you can reach the last index, or false otherwise. 6 | 7 | Example 1: 8 | 9 | Input: nums = [2,3,1,1,4] 10 | Output: true 11 | Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. 12 | 13 | Example 2: 14 | 15 | Input: nums = [3,2,1,0,4] 16 | Output: false 17 | Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index. 18 | 19 | */ 20 | 21 | class Solution { 22 | public: 23 | bool canJump(vector& nums) { 24 | int n = nums.size(); 25 | int vis = n-1; 26 | 27 | for(int i = n-2; i >= 0; i--) { 28 | if(i+nums[i] >= vis) 29 | vis = i; 30 | } 31 | 32 | return vis==0; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/October-2021/5. Climbing Stairs.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are climbing a staircase. It takes n steps to reach the top. 3 | Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 4 | 5 | Example 1: 6 | Input: n = 2 7 | Output: 2 8 | Explanation: There are two ways to climb to the top. 9 | 1. 1 step + 1 step 10 | 2. 2 steps 11 | 12 | Example 2: 13 | Input: n = 3 14 | Output: 3 15 | Explanation: There are three ways to climb to the top. 16 | 1. 1 step + 1 step + 1 step 17 | 2. 1 step + 2 steps 18 | 3. 2 steps + 1 step 19 | 20 | Constraints: 21 | 1 <= n <= 45 22 | */ 23 | 24 | // Fastest solution using Fast Fibonacci technique (O(log n)) 25 | class Solution { 26 | public: 27 | unordered_map F; 28 | 29 | int f(int n) 30 | { 31 | if (F.find(n) != F.end()) return F[n]; 32 | int k = (n>>1); 33 | 34 | if (n&1) 35 | return F[n] = (f(k-1)*f(k) + f(k)*f(k+1)); 36 | else 37 | return F[n] = (f(k-1)*f(k-1) + f(k)*f(k)); 38 | } 39 | 40 | int climbStairs(int n) 41 | { 42 | F[0] = F[1] = 1; 43 | return f(n); 44 | } 45 | }; -------------------------------------------------------------------------------- /Leetcode Daily Challenge/October-2021/6. Duplicates In Array.cpp: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice, 4 | return an array of all the integers that appears twice. 5 | You must write an algorithm that runs in O(n) time and uses only constant extra space. 6 | 7 | Example 1: 8 | Input: nums = [4,3,2,7,8,2,3,1] 9 | Output: [2,3] 10 | 11 | Example 2: 12 | Input: nums = [1,1,2] 13 | Output: [1] 14 | */ 15 | 16 | class Solution { 17 | public: 18 | vector findDuplicates(vector& nums) { 19 | unordered_mapmp; 20 | 21 | for(int i = 0 ; i < nums.size(); i++){ 22 | if(mp.find(nums[i])!= mp.end()){ 23 | mp[nums[i]]++; 24 | } 25 | else{ 26 | mp.insert({nums[i],1}); 27 | } 28 | } 29 | vectorans; 30 | for(auto it : mp){ 31 | if(it.second == 2){ 32 | ans.push_back(it.first); 33 | } 34 | } 35 | 36 | return ans; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/README.md: -------------------------------------------------------------------------------- 1 | # LEETCODE DAILY CHALLENGES 2 | 3 | ### 2020 4 | 5 | - [October](./October-2020) 6 | - [November](./November-2020) 7 | - [December](./December-2020) 8 | 9 | ### 2021 10 | 11 | - [January](./January-2021) 12 | - [February](./February-2021) 13 | - [March](./March-2021) 14 | - [April](./April-2021) 15 | - [May](./May-2021) 16 | - [June](./June-2021) 17 | - [July](./July-2021) 18 | - [August](./August-2021) 19 | - [September](./September-2021) 20 | - [October](./October-2021) 21 | -------------------------------------------------------------------------------- /Leetcode Daily Challenge/September-2021/13. Maximum Number of Balloons.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Maximum Number of Balloons 3 | ========================== 4 | 5 | Given a string text, you want to use the characters of text to form as many instances of the word "balloon" as possible. 6 | 7 | You can use each character in text at most once. Return the maximum number of instances that can be formed. 8 | 9 | Example 1: 10 | Input: text = "nlaebolko" 11 | Output: 1 12 | 13 | Example 2: 14 | Input: text = "loonbalxballpoon" 15 | Output: 2 16 | 17 | Example 3: 18 | Input: text = "leetcode" 19 | Output: 0 20 | 21 | Constraints: 22 | 1 <= text.length <= 104 23 | text consists of lower case English letters only. 24 | 25 | Hint #1 26 | Count the frequency of letters in the given string. 27 | 28 | Hint #2 29 | Find the letter than can make the minimum number of instances of the word "balloon". 30 | */ 31 | 32 | class Solution { 33 | public: 34 | int maxNumberOfBalloons(string text) { 35 | int b = 0, a = 0, l = 0, o = 0, n = 0; 36 | 37 | for(auto& i: text) { 38 | if(i == 'b') b++; 39 | else if(i == 'a') a++; 40 | else if(i == 'l') l++; 41 | else if(i == 'o') o++; 42 | else if(i == 'n') n++; 43 | } 44 | 45 | return min({ b, a, l/2, o/2, n }); 46 | } 47 | }; -------------------------------------------------------------------------------- /Leetcode Daily Challenge/September-2021/21. Max Consecutive Ones.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Max Consecutive Ones 3 | ==================== 4 | 5 | Given a binary array nums, return the maximum number of consecutive 1's in the array. 6 | 7 | Example 1: 8 | Input: nums = [1,1,0,1,1,1] 9 | Output: 3 10 | Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. 11 | 12 | Example 2: 13 | Input: nums = [1,0,1,1,0,1] 14 | Output: 2 15 | 16 | Constraints: 17 | 1 <= nums.length <= 105 18 | nums[i] is either 0 or 1. 19 | */ 20 | 21 | class Solution { 22 | public: 23 | int findMaxConsecutiveOnes(vector& A) { 24 | int ans = 0, i = 0; 25 | 26 | while(i < A.size()) { 27 | 28 | while(i < A.size() && A[i] != 1) i++; 29 | 30 | int count = 0; 31 | while(i < A.size() && A[i] == 1) { 32 | i++; 33 | count++; 34 | } 35 | 36 | ans = max(ans, count); 37 | } 38 | 39 | return ans; 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /Leetcode Top Interview Questions/solutions/Best Time to Buy and Sell Stock.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Best Time to Buy and Sell Stock 3 | =============================== 4 | 5 | Say you have an array for which the ith element is the price of a given stock on day i. 6 | 7 | If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. 8 | 9 | Note that you cannot sell a stock before you buy one. 10 | 11 | Example 1: 12 | Input: [7,1,5,3,6,4] 13 | Output: 5 14 | Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. 15 | Not 7-1 = 6, as selling price needs to be larger than buying price. 16 | 17 | Example 2: 18 | Input: [7,6,4,3,1] 19 | Output: 0 20 | Explanation: In this case, no transaction is done, i.e. max profit = 0. 21 | 22 | */ 23 | 24 | class Solution 25 | { 26 | public: 27 | int maxProfit(vector &prices) 28 | { 29 | int mi = INT_MAX; 30 | int profit = 0; 31 | for (auto i : prices) 32 | { 33 | mi = min(mi, i); 34 | profit = max(profit, i - mi); 35 | } 36 | 37 | return profit; 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /Leetcode Top Interview Questions/solutions/Climbing Stairs.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Climbing Stairs 3 | =============== 4 | 5 | You are climbing a stair case. It takes n steps to reach to the top. 6 | 7 | Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 8 | 9 | Example 1: 10 | Input: 2 11 | Output: 2 12 | Explanation: There are two ways to climb to the top. 13 | 1. 1 step + 1 step 14 | 2. 2 steps 15 | 16 | Example 2: 17 | Input: 3 18 | Output: 3 19 | Explanation: There are three ways to climb to the top. 20 | 1. 1 step + 1 step + 1 step 21 | 2. 1 step + 2 steps 22 | 3. 2 steps + 1 step 23 | 24 | 25 | Constraints: 26 | 1 <= n <= 45 27 | 28 | Hint #1 29 | To reach nth step, what could have been your previous steps? (Think about the step sizes) 30 | */ 31 | 32 | class Solution 33 | { 34 | public: 35 | int climbStairs(int n) 36 | { 37 | if (n == 1) 38 | return 1; 39 | 40 | vector dp(n + 1, 0); 41 | dp[1] = 1; 42 | dp[2] = 2; 43 | 44 | for (int i = 3; i <= n; i++) 45 | dp[i] = dp[i - 1] + dp[i - 2]; 46 | return dp[n]; 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /Leetcode Top Interview Questions/solutions/Coin Change.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Coin Change 3 | ========== 4 | 5 | You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. 6 | 7 | You may assume that you have an infinite number of each kind of coin. 8 | 9 | Example 1: 10 | Input: coins = [1,2,5], amount = 11 11 | Output: 3 12 | Explanation: 11 = 5 + 5 + 1 13 | 14 | Example 2: 15 | Input: coins = [2], amount = 3 16 | Output: -1 17 | 18 | Example 3: 19 | Input: coins = [1], amount = 0 20 | Output: 0 21 | 22 | Example 4: 23 | Input: coins = [1], amount = 1 24 | Output: 1 25 | 26 | Example 5: 27 | Input: coins = [1], amount = 2 28 | Output: 2 29 | 30 | Constraints: 31 | 1 <= coins.length <= 12 32 | 1 <= coins[i] <= 231 - 1 33 | 0 <= amount <= 104 34 | */ 35 | 36 | class Solution 37 | { 38 | public: 39 | int coinChange(vector &coins, int amount) 40 | { 41 | vector dp(amount + 1, amount + 1); 42 | dp[0] = 0; 43 | 44 | for (int i = 1; i <= amount; ++i) 45 | { 46 | for (int coin : coins) 47 | { 48 | if (coin <= i) 49 | dp[i] = min(dp[i], 1 + dp[i - coin]); 50 | } 51 | } 52 | 53 | return dp[amount] == amount + 1 ? -1 : dp[amount]; 54 | } 55 | }; 56 | -------------------------------------------------------------------------------- /Leetcode Top Interview Questions/solutions/Contains Duplicate.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Contains Duplicate 3 | ================== 4 | 5 | Given an array of integers, find if the array contains any duplicates. 6 | 7 | Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. 8 | 9 | Example 1: 10 | Input: [1,2,3,1] 11 | Output: true 12 | 13 | Example 2: 14 | Input: [1,2,3,4] 15 | Output: false 16 | 17 | Example 3: 18 | Input: [1,1,1,3,3,4,3,2,4,2] 19 | Output: true 20 | */ 21 | 22 | class Solution 23 | { 24 | public: 25 | bool containsDuplicate(vector &nums) 26 | { 27 | unordered_map map; 28 | for (int i = 0; i < nums.size(); ++i) 29 | map[nums[i]]++; 30 | for (int i = 0; i < nums.size(); ++i) 31 | if (map[nums[i]] > 1) 32 | return true; 33 | return false; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /Leetcode Top Interview Questions/solutions/Excel Sheet Column Number.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Excel Sheet Column Number 3 | ======================== 4 | 5 | Given a column title as appear in an Excel sheet, return its corresponding column number. 6 | For example: 7 | A -> 1 8 | B -> 2 9 | C -> 3 10 | ... 11 | Z -> 26 12 | AA -> 27 13 | AB -> 28 14 | ... 15 | 16 | Example 1: 17 | Input: "A" 18 | Output: 1 19 | 20 | Example 2: 21 | Input: "AB" 22 | Output: 28 23 | 24 | Example 3: 25 | Input: "ZY" 26 | Output: 701 27 | 28 | Constraints: 29 | 1 <= s.length <= 7 30 | s consists only of uppercase English letters. 31 | s is between "A" and "FXSHRXW". 32 | */ 33 | 34 | class Solution 35 | { 36 | public: 37 | int titleToNumber(string s) 38 | { 39 | int ans = 0; 40 | for (auto &i : s) 41 | ans = 26 * ans + (i - 'A' + 1); 42 | return ans; 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /Leetcode Top Interview Questions/solutions/Find First and Last Position of Element in Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | #Hacktoberfest2021 3 | 4 | Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. 5 | 6 | If target is not found in the array, return [-1, -1]. 7 | 8 | You must write an algorithm with O(log n) runtime complexity. 9 | 10 | 11 | 12 | Example 1: 13 | 14 | Input: nums = [5,7,7,8,8,10], target = 8 15 | Output: [3,4] 16 | Example 2: 17 | 18 | Input: nums = [5,7,7,8,8,10], target = 6 19 | Output: [-1,-1] 20 | */ 21 | // 15ms faster then other codes on leetcode 22 | 23 | class Solution { 24 | public: 25 | vector searchRange(vector& nums, int target) { 26 | int idx1 = lower_bound(nums, target); 27 | int idx2 = lower_bound(nums, target+1)-1; 28 | if (idx1 < nums.size() && nums[idx1] == target) 29 | return {idx1, idx2}; 30 | else 31 | return {-1, -1}; 32 | } 33 | 34 | int lower_bound(vector& nums, int target) { 35 | int l = 0, r = nums.size()-1; 36 | while (l <= r) { 37 | int mid = (r-l)/2+l; 38 | if (nums[mid] < target) 39 | l = mid+1; 40 | else 41 | r = mid-1; 42 | } 43 | return l; 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /Leetcode Top Interview Questions/solutions/Find Peak Element.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Find Peak Element 3 | ================= 4 | 5 | A peak element is an element that is greater than its neighbors. 6 | Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index. 7 | The array may contain multiple peaks, in that case return the index to any one of the peaks is fine. 8 | 9 | You may imagine that nums[-1] = nums[n] = -∞. 10 | 11 | Example 1: 12 | Input: nums = [1,2,3,1] 13 | Output: 2 14 | Explanation: 3 is a peak element and your function should return the index number 2. 15 | 16 | Example 2: 17 | Input: nums = [1,2,1,3,5,6,4] 18 | Output: 1 or 5 19 | Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6. 20 | 21 | Follow up: Your solution should be in logarithmic complexity. 22 | */ 23 | 24 | class Solution 25 | { 26 | public: 27 | int findPeakElement(vector &nums) 28 | { 29 | if (nums.size() <= 1) 30 | return 0; 31 | if (nums.size() == 2) 32 | return nums[0] > nums[1] ? 0 : 1; 33 | 34 | int n = nums.size(); 35 | int left = 0, right = n - 1; 36 | while (left < right) 37 | { 38 | int mid = (left + right) / 2; 39 | if (nums[mid] > nums[mid + 1]) 40 | right = mid; 41 | else 42 | left = mid + 1; 43 | } 44 | 45 | return left; 46 | } 47 | }; 48 | -------------------------------------------------------------------------------- /Leetcode Top Interview Questions/solutions/First Missing Positive.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an unsorted integer array nums, return the smallest missing positive integer. 3 | You must implement an algorithm that runs in O(n) time and uses constant extra space. 4 | 5 | Example 1: 6 | Input: nums = [1,2,0] 7 | Output: 3 8 | 9 | Example 2: 10 | Input: nums = [3,4,-1,1] 11 | Output: 2 12 | 13 | Example 3: 14 | Input: nums = [7,8,9,11,12] 15 | Output: 1 16 | 17 | Constraints: 18 | 1 <= nums.length <= 5 * 105 19 | -231 <= nums[i] <= 231 - 1 20 | 21 | */ 22 | 23 | class Solution { 24 | public: 25 | int firstMissingPositive(vector& nums) { 26 | int i=1; 27 | while(i<=nums.size()){ 28 | if(nums[i-1]!=i && nums[i-1]>=1 && nums[i-1]<=nums.size()){ 29 | if(nums[nums[i-1]-1]==nums[i-1] || nums[i-1]==0){ 30 | i++; 31 | continue; 32 | } 33 | swap(nums[nums[i-1]-1],nums[i-1]); 34 | } 35 | else 36 | i++; 37 | } 38 | for(int i=1;i<=nums.size();i++){ 39 | if(i!=nums[i-1]) 40 | return i; 41 | } 42 | return nums.size()+1; 43 | } 44 | }; -------------------------------------------------------------------------------- /Leetcode Top Interview Questions/solutions/First Unique Character in a String.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | First Unique Character in a String 3 | ================================== 4 | 5 | Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1. 6 | 7 | Examples: 8 | s = "leetcode" 9 | return 0. 10 | 11 | s = "loveleetcode" 12 | return 2. 13 | 14 | 15 | Note: You may assume the string contains only lowercase English letters. 16 | */ 17 | 18 | class Solution 19 | { 20 | public: 21 | int firstUniqChar(string s) 22 | { 23 | unordered_map Map; 24 | for (auto ch : s) 25 | Map[ch]++; 26 | for (auto i = 0; i < s.size(); ++i) 27 | if (Map[s[i]] == 1) 28 | return i; 29 | return -1; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Leetcode Top Interview Questions/solutions/Fizz Buzz.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Fizz Buzz 3 | ========= 4 | 5 | Write a program that outputs the string representation of numbers from 1 to n. 6 | 7 | But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”. 8 | 9 | Example: 10 | 11 | n = 15, 12 | 13 | Return: 14 | [ 15 | "1", 16 | "2", 17 | "Fizz", 18 | "4", 19 | "Buzz", 20 | "Fizz", 21 | "7", 22 | "8", 23 | "Fizz", 24 | "Buzz", 25 | "11", 26 | "Fizz", 27 | "13", 28 | "14", 29 | "FizzBuzz" 30 | ] 31 | */ 32 | 33 | class Solution 34 | { 35 | public: 36 | vector fizzBuzz(int n) 37 | { 38 | vector ans; 39 | for (int i = 1; i <= n; ++i) 40 | { 41 | if (i % 15 == 0) 42 | ans.push_back("FizzBuzz"); 43 | else if (i % 5 == 0) 44 | ans.push_back("Buzz"); 45 | else if (i % 3 == 0) 46 | ans.push_back("Fizz"); 47 | else 48 | ans.push_back(to_string(i)); 49 | } 50 | return ans; 51 | } 52 | }; 53 | -------------------------------------------------------------------------------- /Leetcode Top Interview Questions/solutions/Generate Parentheses.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Generate Parentheses 3 | ==================== 4 | 5 | Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 6 | 7 | Example 1: 8 | Input: n = 3 9 | Output: ["((()))","(()())","(())()","()(())","()()()"] 10 | 11 | Example 2: 12 | Input: n = 1 13 | Output: ["()"] 14 | 15 | Constraints: 16 | 1 <= n <= 8 17 | */ 18 | 19 | class Solution 20 | { 21 | void backtrack(vector &ans, int n, int open, int close, string out = "") 22 | { 23 | if (out.length() == n * 2) 24 | { 25 | ans.push_back(out); 26 | return; 27 | } 28 | 29 | if (open < n) 30 | backtrack(ans, n, open + 1, close, out + "("); 31 | if (close < open) 32 | backtrack(ans, n, open, close + 1, out + ")"); 33 | } 34 | 35 | public: 36 | vector generateParenthesis(int n) 37 | { 38 | vector ans; 39 | backtrack(ans, n, 0, 0); 40 | return ans; 41 | } 42 | }; -------------------------------------------------------------------------------- /Leetcode Top Interview Questions/solutions/Hamming Distance.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Hamming Distance 3 | ================ 4 | 5 | The Hamming distance between two integers is the number of positions at which the corresponding bits are different. 6 | 7 | Given two integers x and y, calculate the Hamming distance. 8 | 9 | Note: 10 | 0 ≤ x, y < 231. 11 | 12 | Example: 13 | Input: x = 1, y = 4 14 | Output: 2 15 | 16 | Explanation: 17 | 1 (0 0 0 1) 18 | 4 (0 1 0 0) 19 | ↑ ↑ 20 | 21 | The above arrows point to positions where the corresponding bits are different. 22 | */ 23 | 24 | class Solution 25 | { 26 | public: 27 | int hammingDistance(int x, int y) 28 | { 29 | int ans = 0; 30 | while (x || y) 31 | { 32 | if (x & 1 ^ y & 1) 33 | ans++; 34 | x = x >> 1; 35 | y = y >> 1; 36 | } 37 | return ans; 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /Leetcode Top Interview Questions/solutions/Happy Number.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Happy Number 3 | ============ 4 | 5 | Write an algorithm to determine if a number n is "happy". 6 | 7 | A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. 8 | 9 | Return True if n is a happy number, and False if not. 10 | 11 | Example: 12 | Input: 19 13 | Output: true 14 | Explanation: 15 | 12 + 92 = 82 16 | 82 + 22 = 68 17 | 62 + 82 = 100 18 | 12 + 02 + 02 = 1 19 | */ 20 | 21 | class Solution 22 | { 23 | bool recursion(int n, set &s) 24 | { 25 | if (n == 0) 26 | return false; 27 | if (n == 1) 28 | return true; 29 | if (s.find(n) != s.end()) 30 | return false; 31 | 32 | s.insert(n); 33 | int newNum = 0; 34 | while (n) 35 | { 36 | int digit = n % 10; 37 | n = n / 10; 38 | newNum += digit * digit; 39 | } 40 | 41 | return recursion(newNum, s); 42 | } 43 | 44 | public: 45 | bool isHappy(int n) 46 | { 47 | set s; 48 | return recursion(n, s); 49 | } 50 | }; 51 | -------------------------------------------------------------------------------- /Leetcode Top Interview Questions/solutions/Jump Game.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Jump Game 3 | ========= 4 | 5 | Given an array of non-negative integers, you are initially positioned at the first index of the array. 6 | 7 | Each element in the array represents your maximum jump length at that position. 8 | Determine if you are able to reach the last index. 9 | 10 | Example 1: 11 | Input: nums = [2,3,1,1,4] 12 | Output: true 13 | Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. 14 | 15 | Example 2: 16 | Input: nums = [3,2,1,0,4] 17 | Output: false 18 | Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index. 19 | 20 | Constraints: 21 | 1 <= nums.length <= 3 * 10^4 22 | 0 <= nums[i][j] <= 10^5 23 | */ 24 | 25 | class Solution 26 | { 27 | public: 28 | bool canJump(vector &nums) 29 | { 30 | if (nums.size() <= 1) 31 | return true; 32 | 33 | int n = nums.size(); 34 | int last_reachable = n - 1; 35 | 36 | for (int i = n - 2; i >= 0; --i) 37 | { 38 | if (i + nums[i] >= last_reachable) 39 | last_reachable = i; 40 | } 41 | 42 | return last_reachable == 0; 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /Leetcode Top Interview Questions/solutions/Kth Largest Element in an Array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Kth Largest Element in an Array 3 | =============================== 4 | 5 | Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. 6 | 7 | Example 1: 8 | Input: [3,2,1,5,6,4] and k = 2 9 | Output: 5 10 | 11 | Example 2: 12 | Input: [3,2,3,1,2,4,5,5,6] and k = 4 13 | Output: 4 14 | 15 | Note: 16 | You may assume k is always valid, 1 ≤ k ≤ array's length. 17 | */ 18 | 19 | class Solution 20 | { 21 | public: 22 | int findKthLargest(vector &nums, int k) 23 | { 24 | priority_queue pq; 25 | for (auto &i : nums) 26 | pq.push(i); 27 | 28 | while (--k > 0) 29 | pq.pop(); 30 | return pq.top(); 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /Leetcode Top Interview Questions/solutions/Kth Missing Positive Number.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Kth Missing Positive Number 3 | 4 | Given an array arr of positive integers sorted in a strictly increasing order, and an integer k. 5 | Find the kth positive integer that is missing from this array. 6 | 7 | Example 1: 8 | Input: arr = [2,3,4,7,11], k = 5 9 | Output: 9 10 | Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive integer is 9. 11 | 12 | Example 2: 13 | Input: arr = [1,2,3,4], k = 2 14 | Output: 6 15 | Explanation: The missing positive integers are [5,6,7,...]. The 2nd missing positive integer is 6. 16 | 17 | Constraints: 18 | - 1 <= arr.length <= 1000 19 | 1 <= arr[i] <= 1000 20 | 1 <= k <= 1000 21 | arr[i] < arr[j] for 1 <= i < j <= arr.length 22 | 23 | */ 24 | 25 | class Solution { 26 | public: 27 | int findKthPositive(vector& arr, int k) { 28 | int s=0,e=arr.size()-1; 29 | while(s<=e){ 30 | int mid=s+(e-s)/2; 31 | if(arr[mid]-mid-1> t(n+1, vector(m+1, 0)); 6 | 7 | for (int i = 1; i <= n; i++) { 8 | for (int j = 1; j <= m; j++) { 9 | if (s1[i-1] == s2[j-1]) { 10 | t[i][j] = 1 + t[i-1][j-1]; 11 | } else { 12 | t[i][j] = max(t[i-1][j], t[i][j-1]); 13 | } 14 | } 15 | } 16 | 17 | return t[n][m]; 18 | } 19 | }; -------------------------------------------------------------------------------- /Leetcode Top Interview Questions/solutions/Majority Element II.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Majority Element II 3 | =================== 4 | 5 | Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. 6 | Follow-up: Could you solve the problem in linear time and in O(1) space? 7 | 8 | Example 1: 9 | Input: nums = [3,2,3] 10 | Output: [3] 11 | 12 | Example 2: 13 | Input: nums = [1] 14 | Output: [1] 15 | 16 | Example 3: 17 | Input: nums = [1,2] 18 | Output: [1,2] 19 | 20 | Constraints: 21 | 1 <= nums.length <= 5 * 104 22 | -109 <= nums[i] <= 109 23 | */ 24 | 25 | class Solution 26 | { 27 | public: 28 | vector majorityElement(vector &nums) 29 | { 30 | vector ans; 31 | sort(nums.begin(), nums.end()); 32 | 33 | int i = 0; 34 | while (i < nums.size()) 35 | { 36 | int up = upper_bound(nums.begin(), nums.end(), nums[i]) - nums.begin(); 37 | int low = lower_bound(nums.begin(), nums.end(), nums[i]) - nums.begin(); 38 | if (up - low > nums.size() / 3) 39 | ans.push_back(nums[i]); 40 | 41 | i = up; 42 | } 43 | 44 | return ans; 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /Leetcode Top Interview Questions/solutions/Majority Element.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Majority Element 3 | ================ 4 | 5 | Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. 6 | You may assume that the array is non-empty and the majority element always exist in the array. 7 | 8 | Example 1: 9 | Input: [3,2,3] 10 | Output: 3 11 | 12 | Example 2: 13 | Input: [2,2,1,1,1,2,2] 14 | Output: 2 15 | */ 16 | 17 | class Solution 18 | { 19 | public: 20 | int majorityElement(vector &nums) 21 | { 22 | int ans = 0, ma = INT_MIN; 23 | sort(nums.begin(), nums.end()); 24 | int i = 0; 25 | while (i < nums.size()) 26 | { 27 | int up = upper_bound(nums.begin(), nums.end(), nums[i]) - nums.begin(); 28 | int low = lower_bound(nums.begin(), nums.end(), nums[i]) - nums.begin(); 29 | if (up - low > ma) 30 | { 31 | ans = nums[i]; 32 | ma = up - low; 33 | } 34 | i = up; 35 | } 36 | 37 | return ans; 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /Leetcode Top Interview Questions/solutions/Maximum Depth of Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Maximum Depth of Binary Tree 3 | ============================ 4 | 5 | Given a binary tree, find its maximum depth. 6 | 7 | The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 8 | 9 | Note: A leaf is a node with no children. 10 | 11 | Example: 12 | Given binary tree [3,9,20,null,null,15,7], 13 | 14 | 3 15 | / \ 16 | 9 20 17 | / \ 18 | 15 7 19 | return its depth = 3. 20 | */ 21 | 22 | /** 23 | * Definition for a binary tree node. 24 | * struct TreeNode { 25 | * int val; 26 | * TreeNode *left; 27 | * TreeNode *right; 28 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 29 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 30 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 31 | * }; 32 | */ 33 | 34 | class Solution 35 | { 36 | public: 37 | int maxDepth(TreeNode *root) 38 | { 39 | if (!root) 40 | return 0; 41 | int ans = 0; 42 | if (root->left) 43 | ans = max(ans, maxDepth(root->left)); 44 | if (root->right) 45 | ans = max(ans, maxDepth(root->right)); 46 | return ans + 1; 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /Leetcode Top Interview Questions/solutions/Maximum Subarray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Maximum Subarray 3 | =============== 4 | 5 | Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. 6 | 7 | Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle. 8 | 9 | 10 | Example 1: 11 | Input: nums = [-2,1,-3,4,-1,2,1,-5,4] 12 | Output: 6 13 | Explanation: [4,-1,2,1] has the largest sum = 6. 14 | 15 | Example 2: 16 | Input: nums = [1] 17 | Output: 1 18 | 19 | Example 3: 20 | Input: nums = [0] 21 | Output: 0 22 | 23 | Example 4: 24 | Input: nums = [-1] 25 | Output: -1 26 | 27 | Example 5: 28 | Input: nums = [-2147483647] 29 | Output: -2147483647 30 | 31 | 32 | Constraints: 33 | 1 <= nums.length <= 2 * 104 34 | -231 <= nums[i] <= 231 - 1 35 | */ 36 | 37 | class Solution 38 | { 39 | public: 40 | int maxSubArray(vector &nums) 41 | { 42 | int n = nums.size(); 43 | if (n == 0) 44 | return 0; 45 | 46 | vector dp(n, 0); 47 | dp[0] = nums[0]; 48 | int ans = nums[0]; 49 | 50 | for (int i = 1; i < n; ++i) 51 | { 52 | dp[i] = max(nums[i], nums[i] + dp[i - 1]); 53 | ans = max(ans, dp[i]); 54 | } 55 | return ans; 56 | } 57 | }; 58 | -------------------------------------------------------------------------------- /Leetcode Top Interview Questions/solutions/Pascals Triangle.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Pascal's Triangle 3 | ================= 4 | 5 | Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. 6 | In Pascal's triangle, each number is the sum of the two numbers directly above it. 7 | 8 | Example: 9 | 10 | Input: 5 11 | Output: 12 | [ 13 | [1], 14 | [1,1], 15 | [1,2,1], 16 | [1,3,3,1], 17 | [1,4,6,4,1] 18 | ] 19 | */ 20 | 21 | class Solution 22 | { 23 | public: 24 | vector> generate(int n) 25 | { 26 | if (n == 0) 27 | return {}; 28 | if (n == 1) 29 | return {{1}}; 30 | 31 | vector> ans; 32 | ans.push_back({1}); 33 | ans.push_back({1, 1}); 34 | 35 | for (int i = 3; i <= n; ++i) 36 | { 37 | vector subans; 38 | subans.push_back(1); 39 | for (int j = 1; j <= i - 2; ++j) 40 | subans.push_back(ans[i - 2][j - 1] + ans[i - 2][j]); 41 | subans.push_back(1); 42 | ans.push_back(subans); 43 | } 44 | 45 | return ans; 46 | } 47 | }; 48 | -------------------------------------------------------------------------------- /Leetcode Top Interview Questions/solutions/Permutations II.cpp: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order. 4 | 5 | 6 | 7 | Example 1: 8 | 9 | Input: nums = [1,1,2] 10 | Output: 11 | [[1,1,2], 12 | [1,2,1], 13 | [2,1,1]] 14 | 15 | Example 2: 16 | 17 | Input: nums = [1,2,3] 18 | Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] 19 | 20 | 21 | Constraints: 22 | 23 | 1 <= nums.length <= 8 24 | -10 <= nums[i] <= 10 25 | 26 | 27 | https://en.cppreference.com/w/cpp/algorithm/next_permutation 28 | */ 29 | 30 | class Solution { 31 | public: 32 | vector> permuteUnique(vector& nums) { 33 | vector og{nums}; 34 | vector> answer; 35 | sort(og.begin(), og.end()); 36 | do { 37 | answer.emplace_back(og); 38 | } while(next_permutation(og.begin(), og.end())); 39 | 40 | return answer; 41 | } 42 | }; -------------------------------------------------------------------------------- /Leetcode Top Interview Questions/solutions/Permutations.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Permutations 3 | ============ 4 | 5 | Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order. 6 | 7 | Example 1: 8 | Input: nums = [1,2,3] 9 | Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] 10 | 11 | Example 2: 12 | Input: nums = [0,1] 13 | Output: [[0,1],[1,0]] 14 | 15 | Example 3: 16 | Input: nums = [1] 17 | Output: [[1]] 18 | 19 | 20 | Constraints: 21 | 1 <= nums.length <= 6 22 | -10 <= nums[i] <= 10 23 | All the integers of nums are unique. 24 | */ 25 | 26 | class Solution 27 | { 28 | void permute(vector nums, int i, vector> &ans) 29 | { 30 | if (i == nums.size() - 1) 31 | { 32 | ans.push_back(nums); 33 | return; 34 | } 35 | 36 | for (int it = i; it < nums.size(); ++it) 37 | { 38 | swap(nums[i], nums[it]); 39 | permute(nums, i + 1, ans); 40 | swap(nums[i], nums[it]); 41 | } 42 | } 43 | 44 | public: 45 | vector> permute(vector &nums) 46 | { 47 | vector> ans; 48 | permute(nums, 0, ans); 49 | return ans; 50 | } 51 | }; 52 | -------------------------------------------------------------------------------- /Leetcode Top Interview Questions/solutions/Pow(x, n).cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Pow(x, n) 3 | ========= 4 | 5 | Implement pow(x, n), which calculates x raised to the power n (i.e. xn). 6 | 7 | Example 1: 8 | Input: x = 2.00000, n = 10 9 | Output: 1024.00000 10 | 11 | Example 2: 12 | Input: x = 2.10000, n = 3 13 | Output: 9.26100 14 | 15 | Example 3: 16 | Input: x = 2.00000, n = -2 17 | Output: 0.25000 18 | Explanation: 2-2 = 1/22 = 1/4 = 0.25 19 | 20 | Constraints: 21 | -100.0 < x < 100.0 22 | -231 <= n <= 231-1 23 | -104 <= xn <= 104 24 | */ 25 | 26 | class Solution 27 | { 28 | public: 29 | double myPow(double x, int n) 30 | { 31 | if (n == 0) 32 | return 1; 33 | double t = pow(x, n / 2); 34 | if (n % 2) 35 | return n < 0 ? 1 / x * t * t : x * t * t; 36 | else 37 | return t * t; 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /Leetcode Top Interview Questions/solutions/Power of Four.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Power of Four 3 | ============= 4 | 5 | Given an integer (signed 32 bits), write a function to check whether it is a power of 4. 6 | 7 | Example 1: 8 | Input: 16 9 | Output: true 10 | 11 | Example 2: 12 | Input: 5 13 | Output: false 14 | 15 | Follow up: Could you solve it without loops/recursion? 16 | */ 17 | 18 | class Solution 19 | { 20 | public: 21 | bool isPowerOfFour(int num) 22 | { 23 | return num > 0 && (log10(num) / log10(4)) == floor((log10(num) / log10(4))); 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Leetcode Top Interview Questions/solutions/Power of Three.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Power of Three 3 | ============== 4 | 5 | Given an integer, write a function to determine if it is a power of three. 6 | 7 | Example 1: 8 | Input: 27 9 | Output: true 10 | 11 | Example 2: 12 | Input: 0 13 | Output: false 14 | 15 | Example 3: 16 | Input: 9 17 | Output: true 18 | 19 | Example 4: 20 | Input: 45 21 | Output: false 22 | 23 | Follow up: 24 | Could you do it without using any loop / recursion? 25 | */ 26 | 27 | class Solution 28 | { 29 | bool isPower(int n, int rem) 30 | { 31 | if (n == 0 || rem) 32 | return false; 33 | if (n == 1) 34 | return true; 35 | 36 | return isPower(n / 3, n % 3); 37 | } 38 | 39 | public: 40 | bool isPowerOfThree(int n) 41 | { 42 | return n > 0 && 1162261467 % n == 0; 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /Leetcode Top Interview Questions/solutions/Product of Array Except Self.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Product of Array Except Self 3 | ============================ 4 | 5 | Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. 6 | 7 | Example: 8 | Input: [1,2,3,4] 9 | Output: [24,12,8,6] 10 | Constraint: It's guaranteed that the product of the elements of any prefix or suffix of the array (including the whole array) fits in a 32 bit integer. 11 | 12 | Note: Please solve it without division and in O(n). 13 | 14 | Follow up: 15 | Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.) 16 | */ 17 | 18 | class Solution 19 | { 20 | public: 21 | vector productExceptSelf(vector &nums) 22 | { 23 | int n = nums.size(); 24 | vector left(n, 1), right(n, 1); 25 | 26 | int mult = 1; 27 | for (int i = 1; i < n; ++i) 28 | { 29 | mult = mult * nums[i - 1]; 30 | left[i] = mult; 31 | } 32 | 33 | mult = 1; 34 | for (int i = n - 2; i >= 0; --i) 35 | { 36 | mult = mult * nums[i + 1]; 37 | right[i] = mult; 38 | } 39 | 40 | for (int i = 0; i < n; ++i) 41 | nums[i] = left[i] * right[i]; 42 | 43 | return nums; 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /Leetcode Top Interview Questions/solutions/Repeated DNA Sequences.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findRepeatedDnaSequences(string s) { 4 | unordered_map freq; 5 | vector out; 6 | 7 | if(s.size()<11){ 8 | return out; 9 | } 10 | 11 | for(int i=0; i1){ 18 | out.push_back(x.first); 19 | } 20 | } 21 | 22 | return out; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Leetcode Top Interview Questions/solutions/Reverse Linked List.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Reverse Linked List 3 | =================== 4 | 5 | Reverse a singly linked list. 6 | 7 | Example: 8 | Input: 1->2->3->4->5->NULL 9 | Output: 5->4->3->2->1->NULL 10 | Follow up: 11 | 12 | A linked list can be reversed either iteratively or recursively. Could you implement both? 13 | */ 14 | 15 | /** 16 | * Definition for singly-linked list. 17 | * struct ListNode { 18 | * int val; 19 | * ListNode *next; 20 | * ListNode() : val(0), next(nullptr) {} 21 | * ListNode(int x) : val(x), next(nullptr) {} 22 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 23 | * }; 24 | */ 25 | 26 | class Solution 27 | { 28 | public: 29 | ListNode *reverseList(ListNode *head) 30 | { 31 | if (!head || !head->next) 32 | return head; 33 | if (!head->next->next) 34 | { 35 | auto temp = head->next; 36 | temp->next = head; 37 | head->next = NULL; 38 | head = temp; 39 | return head; 40 | } 41 | else 42 | { 43 | auto a = head, b = head->next, c = head->next->next; 44 | while (b) 45 | { 46 | b->next = a; 47 | a = b; 48 | b = c; 49 | if (c) 50 | c = c->next; 51 | else 52 | break; 53 | } 54 | head->next = NULL; 55 | head = a; 56 | return head; 57 | } 58 | } 59 | }; 60 | -------------------------------------------------------------------------------- /Leetcode Top Interview Questions/solutions/Reverse String.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Reverse String 3 | ============== 4 | 5 | Write a function that reverses a string. The input string is given as an array of characters char[]. 6 | 7 | Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. 8 | 9 | You may assume all the characters consist of printable ascii characters. 10 | 11 | 12 | Example 1: 13 | Input: ["h","e","l","l","o"] 14 | Output: ["o","l","l","e","h"] 15 | 16 | Example 2: 17 | Input: ["H","a","n","n","a","h"] 18 | Output: ["h","a","n","n","a","H"] 19 | 20 | Hint #1 21 | The entire logic for reversing a string is based on using the opposite directional two-pointer approach! 22 | 23 | */ 24 | 25 | class Solution 26 | { 27 | public: 28 | void reverseString(vector &s) 29 | { 30 | int f = 0, b = s.size() - 1; 31 | while (f < b) 32 | { 33 | char ch = s[f]; 34 | s[f] = s[b]; 35 | s[b] = ch; 36 | f++; 37 | b--; 38 | } 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /Leetcode Top Interview Questions/solutions/Search a 2D Matrix II.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Search a 2D Matrix II 3 | ===================== 4 | 5 | Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: 6 | 7 | Integers in each row are sorted in ascending from left to right. 8 | Integers in each column are sorted in ascending from top to bottom. 9 | 10 | Example: 11 | Consider the following matrix: 12 | [ 13 | [1, 4, 7, 11, 15], 14 | [2, 5, 8, 12, 19], 15 | [3, 6, 9, 16, 22], 16 | [10, 13, 14, 17, 24], 17 | [18, 21, 23, 26, 30] 18 | ] 19 | Given target = 5, return true. 20 | Given target = 20, return false. 21 | */ 22 | 23 | class Solution 24 | { 25 | public: 26 | bool searchMatrix(vector> &matrix, int target) 27 | { 28 | if (!matrix.size() || !matrix[0].size()) 29 | return false; 30 | int n = matrix.size(), m = matrix[0].size(); 31 | int r = 0, c = m - 1; 32 | 33 | while (r < n && c >= 0) 34 | { 35 | if (matrix[r][c] == target) 36 | return true; 37 | else if (matrix[r][c] > target) 38 | c--; 39 | else 40 | r++; 41 | } 42 | 43 | return false; 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /Leetcode Top Interview Questions/solutions/Single Number.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Single Number 3 | ============= 4 | 5 | Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. 6 | 7 | Follow up: Could you implement a solution with a linear runtime complexity and without using extra memory? 8 | 9 | 10 | Example 1: 11 | Input: nums = [2,2,1] 12 | Output: 1 13 | 14 | Example 2: 15 | Input: nums = [4,1,2,1,2] 16 | Output: 4 17 | 18 | Example 3: 19 | Input: nums = [1] 20 | Output: 1 21 | 22 | 23 | Constraints: 24 | 1 <= nums.length <= 3 * 104 25 | -3 * 104 <= nums[i] <= 3 * 104 26 | Each element in the array appears twice except for one element which appears only once. 27 | 28 | */ 29 | class Solution 30 | { 31 | public: 32 | int singleNumber(vector &nums) 33 | { 34 | int n = 0; 35 | for (int i = 0; i < nums.size(); ++i) 36 | n ^= nums[i]; 37 | return n; 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /Leetcode Top Interview Questions/solutions/Sliding Window Maximum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector maxSlidingWindow(vector& nums, int k) { 4 | int n = nums.size(); 5 | if (n == 0 || k == 0) return {}; 6 | 7 | vector v(n-k+1); 8 | deque d; 9 | 10 | for (int i = 0; i < n; ++i) { 11 | while (!d.empty() && d.front() <= i-k) d.pop_front(); 12 | while (!d.empty() && nums[d.back()] < nums[i]) d.pop_back(); 13 | d.push_back(i); 14 | if (i >= k-1) v[i+1-k] = nums[d.front()]; 15 | } 16 | return v; 17 | } 18 | 19 | }; 20 | -------------------------------------------------------------------------------- /Leetcode Top Interview Questions/solutions/Sqrt(x).cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Sqrt(x) 3 | ====== 4 | 5 | Given a non-negative integer x, compute and return the square root of x. 6 | 7 | Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned. 8 | 9 | Example 1: 10 | Input: x = 4 11 | Output: 2 12 | 13 | Example 2: 14 | Input: x = 8 15 | Output: 2 16 | Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned. 17 | 18 | Constraints: 19 | 0 <= x <= 231 - 1 20 | 21 | Hint #1 22 | Try exploring all integers. (Credits: @annujoshi) 23 | 24 | Hint #2 25 | Use the sorted property of integers to reduced the search space. (Credits: @annujoshi) 26 | */ 27 | 28 | class Solution 29 | { 30 | public: 31 | int mySqrt(int x) 32 | { 33 | if (x <= 1) 34 | return x; 35 | long long i = 0; 36 | while (i * i <= x) 37 | i++; 38 | return --i; 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /Leetcode Top Interview Questions/solutions/Subsets.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Subsets 3 | ======= 4 | 5 | Given an integer array nums, return all possible subsets (the power set). 6 | The solution set must not contain duplicate subsets. 7 | 8 | Example 1: 9 | Input: nums = [1,2,3] 10 | Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]] 11 | 12 | Example 2: 13 | Input: nums = [0] 14 | Output: [[],[0]] 15 | 16 | 17 | Constraints: 18 | 1 <= nums.length <= 10 19 | -10 <= nums[i] <= 10 20 | */ 21 | 22 | class Solution 23 | { 24 | void subsets(vector> &ans, vector nums, vector out = {}, int i = 0) 25 | { 26 | if (i >= nums.size()) 27 | { 28 | ans.push_back(out); 29 | return; 30 | } 31 | 32 | subsets(ans, nums, out, i + 1); 33 | out.push_back(nums[i]); 34 | subsets(ans, nums, out, i + 1); 35 | out.pop_back(); 36 | } 37 | 38 | public: 39 | vector> subsets(vector &nums) 40 | { 41 | vector> ans; 42 | subsets(ans, nums); 43 | return ans; 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /Leetcode Top Interview Questions/solutions/Sum of Two Integers.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Sum of Two Integers 3 | =================== 4 | 5 | Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. 6 | 7 | Example 1: 8 | Input: a = 1, b = 2 9 | Output: 3 10 | 11 | Example 2: 12 | Input: a = -2, b = 3 13 | Output: 1 14 | */ 15 | 16 | class Solution 17 | { 18 | public: 19 | int getSum(int a, int b) 20 | { 21 | while (b) 22 | { 23 | int carry = a & b; 24 | a = a ^ b; 25 | b = (unsigned)carry << 1; 26 | } 27 | return a; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Leetcode Top Interview Questions/solutions/Top K Frequent Elements.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Top K Frequent Elements 3 | ======================= 4 | 5 | Given a non-empty array of integers, return the k most frequent elements. 6 | 7 | Example 1: 8 | Input: nums = [1,1,1,2,2,3], k = 2 9 | Output: [1,2] 10 | 11 | Example 2: 12 | Input: nums = [1], k = 1 13 | Output: [1] 14 | 15 | Note: 16 | You may assume k is always valid, 1 ≤ k ≤ number of unique elements. 17 | Your algorithm's time complexity must be better than O(n log n), where n is the array's size. 18 | It's guaranteed that the answer is unique, in other words the set of the top k frequent elements is unique. 19 | You can return the answer in any order. 20 | */ 21 | 22 | class Solution 23 | { 24 | public: 25 | vector topKFrequent(vector &nums, int k) 26 | { 27 | unordered_map m; 28 | for (auto &i : nums) 29 | m[i]++; 30 | 31 | priority_queue> pq; 32 | 33 | for (auto it = m.begin(); it != m.end(); ++it) 34 | { 35 | pq.push({it->second, it->first}); 36 | } 37 | 38 | vector ans; 39 | while (k-- > 0) 40 | { 41 | ans.push_back(pq.top().second); 42 | pq.pop(); 43 | } 44 | return ans; 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /Leetcode Top Interview Questions/solutions/Two Sum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Two Sum 3 | ======= 4 | 5 | Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. 6 | 7 | You may assume that each input would have exactly one solution, and you may not use the same element twice. 8 | 9 | You can return the answer in any order. 10 | 11 | 12 | Example 1: 13 | Input: nums = [2,7,11,15], target = 9 14 | Output: [0,1] 15 | Output: Because nums[0] + nums[1] == 9, we return [0, 1]. 16 | 17 | Example 2: 18 | Input: nums = [3,2,4], target = 6 19 | Output: [1,2] 20 | 21 | Example 3: 22 | Input: nums = [3,3], target = 6 23 | Output: [0,1] 24 | 25 | 26 | Constraints: 27 | 2 <= nums.length <= 105 28 | -109 <= nums[i] <= 109 29 | -109 <= target <= 109 30 | Only one valid answer exists. 31 | 32 | */ 33 | 34 | class Solution 35 | { 36 | public: 37 | vector twoSum(vector &nums, int target) 38 | { 39 | unordered_map m; 40 | for (int i = 0; i < nums.size(); ++i) 41 | { 42 | if (m.find(target - nums[i]) != m.end()) 43 | return {m[target - nums[i]] - 1, i}; 44 | else 45 | m[nums[i]] = i + 1; 46 | } 47 | return {}; 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /Leetcode Top Interview Questions/solutions/Valid Anagram.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Valid Anagram 3 | ============= 4 | 5 | Given two strings s and t , write a function to determine if t is an anagram of s. 6 | 7 | Example 1: 8 | Input: s = "anagram", t = "nagaram" 9 | Output: true 10 | 11 | Example 2: 12 | Input: s = "rat", t = "car" 13 | Output: false 14 | 15 | Note: 16 | You may assume the string contains only lowercase alphabets. 17 | 18 | Follow up: 19 | What if the inputs contain unicode characters? How would you adapt your solution to such case? 20 | 21 | */ 22 | 23 | class Solution 24 | { 25 | public: 26 | bool isAnagram(string s, string t) 27 | { 28 | if (s.size() != t.size()) 29 | return false; 30 | unordered_map Map; 31 | for (auto ch : s) 32 | Map[ch]++; 33 | for (auto ch : t) 34 | Map[ch]--; 35 | 36 | for (auto it = Map.begin(); it != Map.end(); ++it) 37 | if (it->second > 0) 38 | return false; 39 | return true; 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /Leetcode Top Interview Questions/solutions/Valid Palindrome.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Valid Palindrome 3 | ================ 4 | 5 | Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. 6 | 7 | Note: For the purpose of this problem, we define empty string as valid palindrome. 8 | 9 | Example 1: 10 | Input: "A man, a plan, a canal: Panama" 11 | Output: true 12 | 13 | Example 2: 14 | Input: "race a car" 15 | Output: false 16 | 17 | Constraints: 18 | s consists only of printable ASCII characters. 19 | 20 | */ 21 | 22 | class Solution 23 | { 24 | public: 25 | bool isPalindrome(string s) 26 | { 27 | int start = 0, end = s.length() - 1; 28 | while (start < end) 29 | { 30 | if (!isalnum(s[start])) 31 | start++; 32 | else if (!isalnum(s[end])) 33 | end--; 34 | else 35 | { 36 | if (tolower(s[start++]) != tolower(s[end--])) 37 | return false; 38 | } 39 | } 40 | return true; 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /Resources/images/Complexity Chart.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sachuverma/DataStructures-Algorithms/c5dddef53cb1784fbeabd913c2affbf7a36b4ea8/Resources/images/Complexity Chart.png -------------------------------------------------------------------------------- /Resources/images/Data Structures.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sachuverma/DataStructures-Algorithms/c5dddef53cb1784fbeabd913c2affbf7a36b4ea8/Resources/images/Data Structures.png -------------------------------------------------------------------------------- /Resources/images/STL Table.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sachuverma/DataStructures-Algorithms/c5dddef53cb1784fbeabd913c2affbf7a36b4ea8/Resources/images/STL Table.png -------------------------------------------------------------------------------- /Striver Sheet/Day-1/Maximum Subarray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Maximum Subarray 3 | ================ 4 | 5 | Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. 6 | 7 | Example 1: 8 | Input: nums = [-2,1,-3,4,-1,2,1,-5,4] 9 | Output: 6 10 | Explanation: [4,-1,2,1] has the largest sum = 6. 11 | 12 | Example 2: 13 | Input: nums = [1] 14 | Output: 1 15 | 16 | Example 3: 17 | Input: nums = [5,4,-1,7,8] 18 | Output: 23 19 | 20 | Constraints: 21 | 1 <= nums.length <= 3 * 104 22 | -105 <= nums[i] <= 105 23 | 24 | Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle. 25 | */ 26 | 27 | class Solution 28 | { 29 | public: 30 | int maxSubArray(vector &nums) 31 | { 32 | int ans = INT_MIN, curr = 0; 33 | for (int i = 0; i < nums.size(); ++i) 34 | { 35 | curr += nums[i]; 36 | ans = max(ans, curr); 37 | if (curr < 0) 38 | curr = 0; 39 | } 40 | return ans; 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /Striver Sheet/Day-1/Merge Two Sorted Arrays.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Merge Two Sorted Arrays 3 | ======================= 4 | 5 | Given two sorted arrays, we need to merge them in O((n+m)*log(n+m)) time with O(1) extra space into a sorted array, when n is the size of the first array, and m is the size of the second array. 6 | 7 | Example: 8 | Input: ar1[] = {10}; 9 | ar2[] = {2, 3}; 10 | Output: ar1[] = {2} 11 | ar2[] = {3, 10} 12 | 13 | Input: ar1[] = {1, 5, 9, 10, 15, 20}; 14 | ar2[] = {2, 3, 8, 13}; 15 | Output: ar1[] = {1, 2, 3, 5, 8, 9} 16 | ar2[] = {10, 13, 15, 20} 17 | */ -------------------------------------------------------------------------------- /Striver Sheet/Day-10/Permutations.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Permutations 3 | ============ 4 | 5 | Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order. 6 | 7 | Example 1: 8 | Input: nums = [1,2,3] 9 | Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] 10 | 11 | Example 2: 12 | Input: nums = [0,1] 13 | Output: [[0,1],[1,0]] 14 | 15 | Example 3: 16 | Input: nums = [1] 17 | Output: [[1]] 18 | 19 | Constraints: 20 | 1 <= nums.length <= 6 21 | -10 <= nums[i] <= 10 22 | All the integers of nums are unique. 23 | */ 24 | 25 | class Solution 26 | { 27 | public: 28 | void dfs(vector nums, int i, vector> &ans) 29 | { 30 | if (i == nums.size() - 1) 31 | { 32 | ans.push_back(nums); 33 | return; 34 | } 35 | 36 | for (int j = i; j < nums.size(); ++j) 37 | { 38 | swap(nums[i], nums[j]); 39 | dfs(nums, i + 1, ans); 40 | swap(nums[i], nums[j]); 41 | } 42 | } 43 | 44 | vector> permute(vector &nums) 45 | { 46 | vector> ans; 47 | dfs(nums, 0, ans); 48 | return ans; 49 | } 50 | }; 51 | -------------------------------------------------------------------------------- /Striver Sheet/Day-12/Counting Bits.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Counting Bits 3 | ============= 4 | 5 | Given an integer num, return an array of the number of 1's in the binary representation of every number in the range [0, num]. 6 | 7 | Example 1: 8 | Input: num = 2 9 | Output: [0,1,1] 10 | Explanation: 11 | 0 --> 0 12 | 1 --> 1 13 | 2 --> 10 14 | 15 | Example 2: 16 | Input: num = 5 17 | Output: [0,1,1,2,1,2] 18 | Explanation: 19 | 0 --> 0 20 | 1 --> 1 21 | 2 --> 10 22 | 3 --> 11 23 | 4 --> 100 24 | 5 --> 101 25 | 26 | Constraints: 27 | 0 <= num <= 105 28 | 29 | Follow up: 30 | It is very easy to come up with a solution with run time O(32n). Can you do it in linear time O(n) and possibly in a single pass? 31 | Could you solve it in O(n) space complexity? 32 | Can you do it without using any built-in function (i.e., like __builtin_popcount in C++)? 33 | */ 34 | 35 | class Solution 36 | { 37 | public: 38 | vector countBits(int num) 39 | { 40 | vector ans(num + 1, 0); 41 | for (int i = 1; i <= num; ++i) 42 | { 43 | ans[i] = ans[i / 2] + i % 2; 44 | } 45 | return ans; 46 | } 47 | }; -------------------------------------------------------------------------------- /Striver Sheet/Day-12/Power of Two.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Power of Two 3 | ============ 4 | 5 | Given an integer n, return true if it is a power of two. Otherwise, return false. 6 | 7 | An integer n is a power of two, if there exists an integer x such that n == 2x. 8 | 9 | Example 1: 10 | Input: n = 1 11 | Output: true 12 | Explanation: 20 = 1 13 | 14 | Example 2: 15 | Input: n = 16 16 | Output: true 17 | Explanation: 24 = 16 18 | 19 | Example 3: 20 | Input: n = 3 21 | Output: false 22 | 23 | Example 4: 24 | Input: n = 4 25 | Output: true 26 | 27 | Example 5: 28 | Input: n = 5 29 | Output: false 30 | 31 | Constraints: 32 | -231 <= n <= 231 - 1 33 | 34 | Follow up: Could you solve it without loops/recursion? 35 | */ 36 | 37 | class Solution 38 | { 39 | public: 40 | bool isPowerOfTwo(int n) 41 | { 42 | if (n <= 0) 43 | return false; 44 | return !(n & n - 1); 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /Striver Sheet/Day-12/Subsets.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Subsets 3 | ======= 4 | 5 | Given an integer array nums of unique elements, return all possible subsets (the power set). 6 | 7 | The solution set must not contain duplicate subsets. Return the solution in any order. 8 | 9 | Example 1: 10 | Input: nums = [1,2,3] 11 | Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]] 12 | 13 | Example 2: 14 | Input: nums = [0] 15 | Output: [[],[0]] 16 | 17 | Constraints: 18 | 1 <= nums.length <= 10 19 | -10 <= nums[i] <= 10 20 | All the numbers of nums are unique. 21 | */ 22 | 23 | class Solution 24 | { 25 | public: 26 | vector> subsets(vector &nums) 27 | { 28 | vector> ans; 29 | int n = nums.size(), p = pow(2, n); 30 | for (int i = 0; i < p; ++i) 31 | { 32 | vector arr; 33 | for (int j = 0; j < n; ++j) 34 | { 35 | if ((i >> j) & 1) 36 | arr.push_back(nums[j]); 37 | } 38 | ans.push_back(arr); 39 | } 40 | return ans; 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /Striver Sheet/Day-13/Valid Parentheses.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Valid Parentheses 3 | ================= 4 | 5 | Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 6 | 7 | An input string is valid if: 8 | 9 | Open brackets must be closed by the same type of brackets. 10 | Open brackets must be closed in the correct order. 11 | 12 | Example 1: 13 | Input: s = "()" 14 | Output: true 15 | 16 | Example 2: 17 | Input: s = "()[]{}" 18 | Output: true 19 | 20 | Example 3: 21 | Input: s = "(]" 22 | Output: false 23 | 24 | Example 4: 25 | Input: s = "([)]" 26 | Output: false 27 | 28 | Example 5: 29 | Input: s = "{[]}" 30 | Output: true 31 | 32 | Constraints: 33 | 1 <= s.length <= 104 34 | s consists of parentheses only '()[]{}'. 35 | */ 36 | 37 | class Solution 38 | { 39 | public: 40 | bool isValid(string s) 41 | { 42 | stack st; 43 | for (auto &i : s) 44 | { 45 | if (i == '(' || i == '{' || i == '[') 46 | st.push(i); 47 | else 48 | { 49 | if (!st.size()) 50 | return false; 51 | if (i == ')' && st.top() == '(') 52 | st.pop(); 53 | else if (i == '}' && st.top() == '{') 54 | st.pop(); 55 | else if (i == ']' && st.top() == '[') 56 | st.pop(); 57 | else 58 | return false; 59 | } 60 | } 61 | return st.size() == 0; 62 | } 63 | }; 64 | -------------------------------------------------------------------------------- /Striver Sheet/Day-15/Implement strStr.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Implement strStr 3 | ================ 4 | 5 | Implement strStr(). 6 | 7 | Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 8 | 9 | Clarification: 10 | What should we return when needle is an empty string? This is a great question to ask during an interview. 11 | 12 | For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf(). 13 | 14 | Example 1: 15 | Input: haystack = "hello", needle = "ll" 16 | Output: 2 17 | 18 | Example 2: 19 | Input: haystack = "aaaaa", needle = "bba" 20 | Output: -1 21 | 22 | Example 3: 23 | Input: haystack = "", needle = "" 24 | Output: 0 25 | 26 | Constraints: 27 | 0 <= haystack.length, needle.length <= 5 * 104 28 | haystack and needle consist of only lower-case English characters. 29 | */ 30 | 31 | class Solution 32 | { 33 | public: 34 | int strStr(string hs, string n) 35 | { 36 | if (n.size() == 0) 37 | return 0; 38 | for (int j = 0; j < hs.size(); ++j) 39 | { 40 | if (hs[j] == n[0]) 41 | { 42 | int i = 1; 43 | while (i < n.size() && hs[j + i] == n[i]) 44 | i++; 45 | if (i == n.size()) 46 | return j; 47 | } 48 | } 49 | return -1; 50 | } 51 | }; 52 | -------------------------------------------------------------------------------- /Striver Sheet/Day-15/Longest Common Prefix.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Longest Common Prefix 3 | ===================== 4 | 5 | Write a function to find the longest common prefix string amongst an array of strings. 6 | 7 | If there is no common prefix, return an empty string "". 8 | 9 | Example 1: 10 | Input: strs = ["flower","flow","flight"] 11 | Output: "fl" 12 | 13 | Example 2: 14 | Input: strs = ["dog","racecar","car"] 15 | Output: "" 16 | Explanation: There is no common prefix among the input strings. 17 | 18 | Constraints: 19 | 1 <= strs.length <= 200 20 | 0 <= strs[i].length <= 200 21 | strs[i] consists of only lower-case English letters. 22 | */ 23 | 24 | class Solution 25 | { 26 | public: 27 | string longestCommonPrefix(vector &strs) 28 | { 29 | string ans; 30 | int minLen = INT_MAX; 31 | for (auto &i : strs) 32 | minLen = min(minLen, (int)i.size()); 33 | for (int i = 0; i < minLen; ++i) 34 | { 35 | int ch = strs[0][i]; 36 | for (int j = 1; j < strs.size(); ++j) 37 | { 38 | if (strs[j][i] != ch) 39 | return ans; 40 | } 41 | ans += ch; 42 | } 43 | return ans; 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /Striver Sheet/Day-16/Valid Anagram.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Valid Anagram 3 | ============== 4 | 5 | Given two strings s and t, return true if t is an anagram of s, and false otherwise. 6 | 7 | Example 1: 8 | Input: s = "anagram", t = "nagaram" 9 | Output: true 10 | 11 | Example 2: 12 | Input: s = "rat", t = "car" 13 | Output: false 14 | 15 | Constraints: 16 | 1 <= s.length, t.length <= 5 * 104 17 | s and t consist of lowercase English letters. 18 | 19 | Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case? 20 | */ 21 | 22 | class Solution 23 | { 24 | public: 25 | bool isAnagram(string s, string t) 26 | { 27 | vector arr(26, 0); 28 | for (auto &i : s) 29 | arr[i - 'a']++; 30 | for (auto &i : t) 31 | arr[i - 'a']--; 32 | for (auto &i : arr) 33 | if (i != 0) 34 | return false; 35 | return true; 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /Striver Sheet/Day-18/Same Tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Same Tree 3 | ========= 4 | 5 | Given the roots of two binary trees p and q, write a function to check if they are the same or not. 6 | 7 | Two binary trees are considered the same if they are structurally identical, and the nodes have the same value. 8 | 9 | Example 1: 10 | Input: p = [1,2,3], q = [1,2,3] 11 | Output: true 12 | 13 | Example 2: 14 | Input: p = [1,2], q = [1,null,2] 15 | Output: false 16 | 17 | Example 3: 18 | Input: p = [1,2,1], q = [1,1,2] 19 | Output: false 20 | 21 | Constraints: 22 | The number of nodes in both trees is in the range [0, 100]. 23 | -104 <= Node.val <= 104 24 | */ 25 | 26 | /** 27 | * Definition for a binary tree node. 28 | * struct TreeNode { 29 | * int val; 30 | * TreeNode *left; 31 | * TreeNode *right; 32 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 33 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 34 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 35 | * }; 36 | */ 37 | 38 | class Solution 39 | { 40 | public: 41 | bool isSameTree(TreeNode *p, TreeNode *q) 42 | { 43 | if (!p && !q) 44 | return true; 45 | if ((!p && q) || (!q && p)) 46 | return false; 47 | if (p->val != q->val) 48 | return false; 49 | return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); 50 | } 51 | }; 52 | -------------------------------------------------------------------------------- /Striver Sheet/Day-2/Best Time to Buy and Sell Stock.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Best Time to Buy and Sell Stock 3 | =============================== 4 | 5 | You are given an array prices where prices[i] is the price of a given stock on the ith day. 6 | 7 | You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. 8 | 9 | Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. 10 | 11 | Example 1: 12 | Input: prices = [7,1,5,3,6,4] 13 | Output: 5 14 | Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. 15 | Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. 16 | 17 | Example 2: 18 | Input: prices = [7,6,4,3,1] 19 | Output: 0 20 | Explanation: In this case, no transactions are done and the max profit = 0. 21 | 22 | Constraints: 23 | 1 <= prices.length <= 105 24 | 0 <= prices[i] <= 104 25 | */ 26 | 27 | class Solution 28 | { 29 | public: 30 | int maxProfit(vector &prices) 31 | { 32 | int ans = 0; 33 | int MIN = INT_MAX; 34 | 35 | for (auto &i : prices) 36 | { 37 | MIN = min(MIN, i); 38 | ans = max(ans, i - MIN); 39 | } 40 | 41 | return ans; 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /Striver Sheet/Day-2/Pascal's Triangle.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Pascal's Triangle 3 | ================= 4 | 5 | Given an integer numRows, return the first numRows of Pascal's triangle. 6 | 7 | In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: 8 | 9 | Example 1: 10 | Input: numRows = 5 11 | Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] 12 | 13 | Example 2: 14 | Input: numRows = 1 15 | Output: [[1]] 16 | 17 | Constraints: 18 | 1 <= numRows <= 30 19 | */ 20 | 21 | class Solution 22 | { 23 | public: 24 | vector> generate(int N) 25 | { 26 | if (N == 1) 27 | return {{1}}; 28 | if (N == 2) 29 | return {{1}, {1, 1}}; 30 | vector> ans = {{1}, {1, 1}}; 31 | vector prev = {1, 1}; 32 | 33 | for (int i = 3; i <= N; ++i) 34 | { 35 | vector curr(i, 1); 36 | for (int j = 1; j < i - 1; ++j) 37 | curr[j] = prev[j - 1] + prev[j]; 38 | ans.push_back(curr); 39 | prev = curr; 40 | } 41 | 42 | return ans; 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /Striver Sheet/Day-20/Search in a Binary Search Tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Search in a Binary Search Tree 3 | ============================== 4 | 5 | You are given the root of a binary search tree (BST) and an integer val. 6 | 7 | Find the node in the BST that the node's value equals val and return the subtree rooted with that node. If such a node does not exist, return null. 8 | 9 | Example 1: 10 | Input: root = [4,2,7,1,3], val = 2 11 | Output: [2,1,3] 12 | 13 | Example 2: 14 | Input: root = [4,2,7,1,3], val = 5 15 | Output: [] 16 | 17 | Constraints: 18 | The number of nodes in the tree is in the range [1, 5000]. 19 | 1 <= Node.val <= 107 20 | root is a binary search tree. 21 | 1 <= val <= 107 22 | */ 23 | 24 | /** 25 | * Definition for a binary tree node. 26 | * struct TreeNode { 27 | * int val; 28 | * TreeNode *left; 29 | * TreeNode *right; 30 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 31 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 32 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 33 | * }; 34 | */ 35 | 36 | class Solution 37 | { 38 | public: 39 | TreeNode *searchBST(TreeNode *root, int val) 40 | { 41 | if (!root) 42 | return NULL; 43 | if (root->val == val) 44 | return root; 45 | else if (root->val > val) 46 | return searchBST(root->left, val); 47 | return searchBST(root->right, val); 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /Striver Sheet/Day-21/Kth largest element in BST.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Kth largest element in BST 3 | ========================== 4 | 5 | Given a Binary search tree. Your task is to complete the function which will return the Kth largest element without doing any modification in Binary Search Tree. 6 | 7 | Example 1: 8 | Input: 9 | 4 10 | / \ 11 | 2 9 12 | k = 2 13 | Output: 4 14 | 15 | Example 2: 16 | Input: 17 | 9 18 | \ 19 | 10 20 | K = 1 21 | Output: 10 22 | Your Task: 23 | You don't need to read input or print anything. Your task is to complete the function kthLargest() which takes the root of the BST and an integer K as inputs and returns the Kth largest element in the given BST. 24 | 25 | Expected Time Complexity: O(H + K). 26 | Expected Auxiliary Space: O(H) 27 | 28 | Constraints: 29 | 1 <= N <= 1000 30 | 1 <= K <= N 31 | */ 32 | 33 | class Solution 34 | { 35 | public: 36 | void inorder(Node *root, vector &arr) 37 | { 38 | if (!root) 39 | return; 40 | inorder(root->left, arr); 41 | arr.push_back(root->data); 42 | inorder(root->right, arr); 43 | } 44 | int kthLargest(Node *root, int K) 45 | { 46 | //Your code here 47 | vector arr; 48 | inorder(root, arr); 49 | return arr[arr.size() - K]; 50 | } 51 | }; -------------------------------------------------------------------------------- /Striver Sheet/Day-21/Largest BST.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Largest BST 3 | =========== 4 | 5 | Given a binary tree. Find the size of its largest subtree that is a Binary Search Tree. 6 | 7 | Example 1: 8 | Input: 9 | 1 10 | / \ 11 | 4 4 12 | / \ 13 | 6 8 14 | Output: 1 15 | Explanation: There's no sub-tree with size 16 | greater than 1 which forms a BST. All the 17 | leaf Nodes are the BSTs with size equal 18 | to 1. 19 | 20 | Example 2: 21 | Input: 6 6 3 N 2 9 3 N 8 8 2 22 | 6 23 | / \ 24 | 6 3 25 | \ / \ 26 | 2 9 3 27 | \ / \ 28 | 8 8 2 29 | Output: 2 30 | Explanation: The following sub-tree is a 31 | BST of size 2: 32 | 2 33 | / \ 34 | N 8 35 | Your Task: 36 | You don't need to read input or print anything. Your task is to complete the function largestBst() that takes the root node of the Binary Tree as its input and returns the size of the largest subtree which is also the BST. If the complete Binary Tree is a BST, return the size of the complete Binary Tree. 37 | 38 | Expected Time Complexity: O(N). 39 | Expected Auxiliary Space: O(Height of the BST). 40 | 41 | Constraints: 42 | 1 <= Number of nodes <= 100000 43 | 1 <= Data of a node <= 1000000 44 | */ 45 | -------------------------------------------------------------------------------- /Striver Sheet/Day-3/Majority Element.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Majority Element 3 | ================ 4 | 5 | Given an array nums of size n, return the majority element. 6 | 7 | The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array. 8 | 9 | Example 1: 10 | Input: nums = [3,2,3] 11 | Output: 3 12 | 13 | Example 2: 14 | Input: nums = [2,2,1,1,1,2,2] 15 | Output: 2 16 | 17 | Constraints: 18 | n == nums.length 19 | 1 <= n <= 5 * 104 20 | -231 <= nums[i] <= 231 - 1 21 | 22 | Follow-up: Could you solve the problem in linear time and in O(1) space? 23 | */ 24 | 25 | class Solution 26 | { 27 | public: 28 | int majorityElement(vector &nums) 29 | { 30 | int elem = nums[0]; 31 | int count = 1; 32 | 33 | for (int i = 1; i < nums.size(); ++i) 34 | { 35 | if (elem == nums[i]) 36 | count++; 37 | else 38 | { 39 | if (count == 0) 40 | { 41 | elem = nums[i]; 42 | count = 1; 43 | } 44 | else 45 | count--; 46 | } 47 | } 48 | return elem; 49 | } 50 | }; 51 | -------------------------------------------------------------------------------- /Striver Sheet/Day-3/Powxn.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Pow(x, n) 3 | ========= 4 | 5 | Implement pow(x, n), which calculates x raised to the power n (i.e., xn). 6 | 7 | Example 1: 8 | Input: x = 2.00000, n = 10 9 | Output: 1024.00000 10 | 11 | Example 2: 12 | Input: x = 2.10000, n = 3 13 | Output: 9.26100 14 | 15 | Example 3: 16 | Input: x = 2.00000, n = -2 17 | Output: 0.25000 18 | Explanation: 2-2 = 1/22 = 1/4 = 0.25 19 | 20 | Constraints: 21 | -100.0 < x < 100.0 22 | -231 <= n <= 231-1 23 | -104 <= xn <= 104 24 | */ 25 | 26 | class Solution 27 | { 28 | public: 29 | double myPow(double x, int n) 30 | { 31 | long long N = abs(n); 32 | double ans = 1.0; 33 | while (N > 0) 34 | { 35 | if (N % 2 == 1) 36 | { 37 | ans = ans * x; 38 | N--; 39 | } 40 | else 41 | { 42 | x = x * x; 43 | N = N / 2; 44 | } 45 | } 46 | 47 | if (n < 0) 48 | return 1.0 / ans; 49 | else 50 | return ans; 51 | } 52 | }; -------------------------------------------------------------------------------- /Striver Sheet/Day-3/Search a 2D Matrix.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Search a 2D Matrix 3 | ================== 4 | 5 | Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: 6 | 7 | Integers in each row are sorted from left to right. 8 | The first integer of each row is greater than the last integer of the previous row. 9 | 10 | Example 1: 11 | Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 12 | Output: true 13 | 14 | Example 2: 15 | Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13 16 | Output: false 17 | 18 | Constraints: 19 | m == matrix.length 20 | n == matrix[i].length 21 | 1 <= m, n <= 100 22 | -104 <= matrix[i][j], target <= 104 23 | */ 24 | 25 | class Solution 26 | { 27 | public: 28 | bool searchMatrix(vector> &matrix, int target) 29 | { 30 | int n = matrix.size(), m = matrix[0].size(); 31 | int r = 0, c = m - 1; 32 | 33 | while (r < n && c >= 0) 34 | { 35 | if (matrix[r][c] == target) 36 | return true; 37 | else if (matrix[r][c] < target) 38 | r++; 39 | else 40 | c--; 41 | } 42 | return false; 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /Striver Sheet/Day-4/Largest subarray with 0 sum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Largest subarray with 0 sum 3 | =========================== 4 | 5 | Given an array having both positive and negative integers. The task is to compute the length of the largest subarray with sum 0. 6 | 7 | Example 1: 8 | Input: 9 | N = 8 10 | A[] = {15,-2,2,-8,1,7,10,23} 11 | Output: 5 12 | Explanation: The largest subarray with 13 | sum 0 will be -2 2 -8 1 7. 14 | Your Task: 15 | You just have to complete the function maxLen() which takes two arguments an array A and n, where n is the size of the array A and returns the length of the largest subarray with 0 sum. 16 | 17 | Expected Time Complexity: O(N*Log(N)). 18 | Expected Auxiliary Space: O(N). 19 | 20 | Constraints: 21 | 1 <= N <= 104 22 | -1000 <= A[i] <= 1000, for each valid i 23 | */ 24 | 25 | int maxLen(int A[], int n) 26 | { 27 | vector prefix(n, 0); 28 | prefix[0] = A[0]; 29 | for (int i = 1; i < n; ++i) 30 | prefix[i] = prefix[i - 1] + A[i]; 31 | 32 | unordered_map m; 33 | int ans = 0; 34 | for (int i = 0; i < n; ++i) 35 | { 36 | if (prefix[i] == 0) 37 | ans = max(ans, i + 1); 38 | if (m.find(prefix[i]) != m.end()) 39 | { 40 | ans = max(ans, i - m[prefix[i]]); 41 | } 42 | else 43 | m[prefix[i]] = i; 44 | } 45 | 46 | return ans; 47 | } 48 | -------------------------------------------------------------------------------- /Striver Sheet/Day-4/Longest Consecutive Sequence.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Longest Consecutive Sequence 3 | ============================ 4 | 5 | Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. 6 | 7 | Example 1: 8 | Input: nums = [100,4,200,1,3,2] 9 | Output: 4 10 | Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4. 11 | 12 | Example 2: 13 | Input: nums = [0,3,7,2,5,8,4,6,0,1] 14 | Output: 9 15 | 16 | Constraints: 17 | 0 <= nums.length <= 104 18 | -109 <= nums[i] <= 109 19 | 20 | Follow up: Could you implement the O(n) solution? 21 | */ 22 | 23 | class Solution 24 | { 25 | public: 26 | int longestConsecutive(vector &nums) 27 | { 28 | int n = nums.size(); 29 | if (n <= 1) 30 | return n; 31 | 32 | int ans = 1; 33 | unordered_set s; 34 | for (auto &i : nums) 35 | s.insert(i); 36 | 37 | for (auto &i : nums) 38 | { 39 | if (s.find(i - 1) != s.end()) 40 | continue; 41 | int num = i; 42 | int count = 1; 43 | while (s.find(num + 1) != s.end()) 44 | { 45 | count++; 46 | num = num + 1; 47 | } 48 | ans = max(ans, count); 49 | } 50 | return ans; 51 | } 52 | }; 53 | -------------------------------------------------------------------------------- /Striver Sheet/Day-4/Longest Substring Without Repeating Characters.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Longest Substring Without Repeating Characters 3 | ============================================== 4 | 5 | Given a string s, find the length of the longest substring without repeating characters. 6 | 7 | Example 1: 8 | Input: s = "abcabcbb" 9 | Output: 3 10 | Explanation: The answer is "abc", with the length of 3. 11 | 12 | Example 2: 13 | Input: s = "bbbbb" 14 | Output: 1 15 | Explanation: The answer is "b", with the length of 1. 16 | 17 | Example 3: 18 | Input: s = "pwwkew" 19 | Output: 3 20 | Explanation: The answer is "wke", with the length of 3. 21 | Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. 22 | 23 | Example 4: 24 | Input: s = "" 25 | Output: 0 26 | 27 | Constraints: 28 | 0 <= s.length <= 5 * 104 29 | s consists of English letters, digits, symbols and spaces. 30 | */ 31 | 32 | class Solution 33 | { 34 | public: 35 | int lengthOfLongestSubstring(string s) 36 | { 37 | int i = 0, j = 0; 38 | int n = s.size(), ans = 0; 39 | 40 | vector freq(256, 0); 41 | while (i < n && j < n) 42 | { 43 | while (freq[s[j]] > 0) 44 | { 45 | freq[s[i]]--; 46 | i++; 47 | } 48 | freq[s[j]]++; 49 | j++; 50 | ans = max(ans, j - i); 51 | } 52 | return ans; 53 | } 54 | }; -------------------------------------------------------------------------------- /Striver Sheet/Day-4/Two Sum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Two Sum 3 | ======= 4 | 5 | Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. 6 | 7 | You may assume that each input would have exactly one solution, and you may not use the same element twice. 8 | 9 | You can return the answer in any order. 10 | 11 | Example 1: 12 | Input: nums = [2,7,11,15], target = 9 13 | Output: [0,1] 14 | Output: Because nums[0] + nums[1] == 9, we return [0, 1]. 15 | 16 | Example 2: 17 | Input: nums = [3,2,4], target = 6 18 | Output: [1,2] 19 | 20 | Example 3: 21 | Input: nums = [3,3], target = 6 22 | Output: [0,1] 23 | 24 | Constraints: 25 | 2 <= nums.length <= 103 26 | -109 <= nums[i] <= 109 27 | -109 <= target <= 109 28 | Only one valid answer exists. 29 | */ 30 | 31 | class Solution 32 | { 33 | public: 34 | vector twoSum(vector &nums, int target) 35 | { 36 | unordered_map prev; 37 | for (int i = 0; i < nums.size(); ++i) 38 | { 39 | int tar = target - nums[i]; 40 | if (prev.find(tar) != prev.end()) 41 | return {prev[tar], i}; 42 | else 43 | prev[nums[i]] = i; 44 | } 45 | return {-1, -1}; 46 | } 47 | }; 48 | -------------------------------------------------------------------------------- /Striver Sheet/Day-5/Reverse Linked List.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Reverse Linked List 3 | =================== 4 | 5 | Given the head of a singly linked list, reverse the list, and return the reversed list. 6 | 7 | Example 1: 8 | Input: head = [1,2,3,4,5] 9 | Output: [5,4,3,2,1] 10 | 11 | Example 2: 12 | Input: head = [1,2] 13 | Output: [2,1] 14 | 15 | Example 3: 16 | Input: head = [] 17 | Output: [] 18 | 19 | Constraints: 20 | The number of nodes in the list is the range [0, 5000]. 21 | -5000 <= Node.val <= 5000 22 | 23 | Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both? 24 | */ 25 | 26 | /** 27 | * Definition for singly-linked list. 28 | * struct ListNode { 29 | * int val; 30 | * ListNode *next; 31 | * ListNode() : val(0), next(nullptr) {} 32 | * ListNode(int x) : val(x), next(nullptr) {} 33 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 34 | * }; 35 | */ 36 | 37 | class Solution 38 | { 39 | public: 40 | ListNode *reverseList(ListNode *head) 41 | { 42 | if (!head || !head->next) 43 | return head; 44 | ListNode *dummy = NULL; 45 | while (head) 46 | { 47 | auto next = head->next; 48 | head->next = dummy; 49 | dummy = head; 50 | if (!next) 51 | break; 52 | head = next; 53 | } 54 | return head; 55 | } 56 | }; -------------------------------------------------------------------------------- /Striver Sheet/Day-7/Max Consecutive Ones.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Max Consecutive Ones 3 | ==================== 4 | 5 | Given a binary array nums, return the maximum number of consecutive 1's in the array. 6 | 7 | Example 1: 8 | Input: nums = [1,1,0,1,1,1] 9 | Output: 3 10 | Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. 11 | 12 | Example 2: 13 | Input: nums = [1,0,1,1,0,1] 14 | Output: 2 15 | 16 | Constraints: 17 | 1 <= nums.length <= 10^5 18 | nums[i] is either 0 or 1. 19 | */ 20 | 21 | class Solution 22 | { 23 | public: 24 | int findMaxConsecutiveOnes(vector &nums) 25 | { 26 | int one = 0; 27 | int count = 0; 28 | int ans = 0; 29 | for (int i = 0; i < nums.size(); ++i) 30 | { 31 | if (nums[i] == 1) 32 | { 33 | if (one == 1) 34 | { 35 | count++; 36 | ans = max(ans, count); 37 | } 38 | else 39 | { 40 | one = 1; 41 | count = 1; 42 | ans = max(ans, 1); 43 | } 44 | } 45 | else 46 | { 47 | count = 0; 48 | one = 0; 49 | } 50 | } 51 | return ans; 52 | } 53 | }; -------------------------------------------------------------------------------- /Striver Sheet/Day-7/Trapping Rain Water.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Trapping Rain Water 3 | ================== 4 | 5 | Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining. 6 | 7 | Example 1: 8 | Input: height = [0,1,0,2,1,0,1,3,2,1,2,1] 9 | Output: 6 10 | Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. 11 | 12 | Example 2: 13 | Input: height = [4,2,0,3,2,5] 14 | Output: 9 15 | 16 | Constraints: 17 | n == height.length 18 | 0 <= n <= 3 * 104 19 | 0 <= height[i] <= 105 20 | */ 21 | 22 | class Solution 23 | { 24 | public: 25 | int trap(vector &h) 26 | { 27 | int n = h.size(); 28 | if (n <= 1) 29 | return 0; 30 | int ans = 0; 31 | int i = 0, j = n - 1; 32 | int left = h[0], right = h[n - 1]; 33 | 34 | while (i <= j) 35 | { 36 | left = max(left, h[i]); 37 | right = max(right, h[j]); 38 | 39 | if (min(left, right) >= h[i]) 40 | ans += min(left, right) - h[i]; 41 | 42 | if (min(left, right) >= h[j]) 43 | ans += min(left, right) - h[j]; 44 | 45 | if (h[i] < h[j]) 46 | i++; 47 | else 48 | j--; 49 | } 50 | 51 | return ans; 52 | } 53 | }; 54 | -------------------------------------------------------------------------------- /Striver Sheet/Day-9/Palindrome Partitioning.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Palindrome Partitioning 3 | ======================= 4 | 5 | Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s. 6 | 7 | A palindrome string is a string that reads the same backward as forward. 8 | 9 | Example 1: 10 | Input: s = "aab" 11 | Output: [["a","a","b"],["aa","b"]] 12 | 13 | Example 2: 14 | Input: s = "a" 15 | Output: [["a"]] 16 | 17 | Constraints: 18 | 1 <= s.length <= 16 19 | s contains only lowercase English letters. 20 | */ 21 | 22 | class Solution 23 | { 24 | public: 25 | bool check(string &s, int i, int j) 26 | { 27 | while (i < j) 28 | { 29 | if (s[i++] != s[j--]) 30 | return false; 31 | } 32 | return true; 33 | } 34 | 35 | void dfs(string &s, int idx, vector> &ans, vector atn) 36 | { 37 | if (s.size() == idx) 38 | { 39 | ans.push_back(atn); 40 | return; 41 | } 42 | 43 | for (int i = idx; i < s.size(); ++i) 44 | { 45 | if (check(s, idx, i)) 46 | { 47 | atn.push_back(s.substr(idx, i - idx + 1)); 48 | dfs(s, i + 1, ans, atn); 49 | atn.pop_back(); 50 | } 51 | } 52 | } 53 | 54 | vector> partition(string s) 55 | { 56 | vector> ans; 57 | dfs(s, 0, ans, {}); 58 | return ans; 59 | } 60 | }; 61 | -------------------------------------------------------------------------------- /Striver Sheet/Day-9/Permutation Sequence.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Permutation Sequence 3 | ==================== 4 | 5 | The set [1, 2, 3, ..., n] contains a total of n! unique permutations. 6 | 7 | By listing and labeling all of the permutations in order, we get the following sequence for n = 3: 8 | "123" 9 | "132" 10 | "213" 11 | "231" 12 | "312" 13 | "321" 14 | Given n and k, return the kth permutation sequence. 15 | 16 | Example 1: 17 | Input: n = 3, k = 3 18 | Output: "213" 19 | 20 | Example 2: 21 | Input: n = 4, k = 9 22 | Output: "2314" 23 | 24 | Example 3: 25 | Input: n = 3, k = 1 26 | Output: "123" 27 | 28 | Constraints: 29 | 1 <= n <= 9 30 | 1 <= k <= n! 31 | */ 32 | 33 | class Solution 34 | { 35 | public: 36 | string getPermutation(int n, int k) 37 | { 38 | vector nums; 39 | int fact = 1; 40 | for (int i = 1; i < n; ++i) 41 | { 42 | nums.push_back(i); 43 | fact *= i; 44 | } 45 | nums.push_back(n); 46 | 47 | string ans; 48 | k = k - 1; 49 | 50 | for (int i = 0; i < n; ++i) 51 | { 52 | int location = k / fact; 53 | ans.push_back(nums[location] + '0'); 54 | nums.erase(nums.begin() + location); 55 | if (nums.size() == 0) 56 | break; 57 | 58 | k = k % fact; 59 | fact = fact / nums.size(); 60 | } 61 | 62 | return ans; 63 | } 64 | }; 65 | -------------------------------------------------------------------------------- /Striver Sheet/Day-9/Subset Sums.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Subset Sums 3 | =========== 4 | 5 | Given a list(Arr) of N integers, print sums of all subsets in it. Output should be printed in increasing order of sums. 6 | 7 | Example 1: 8 | Input: 9 | N = 2 10 | Arr = [2, 3] 11 | Output: 12 | 0 2 3 5 13 | Explanation: 14 | When no elements is taken then Sum = 0. 15 | When only 2 is taken then Sum = 2. 16 | When only 3 is taken then Sum = 3. 17 | When element 2 and 3 are taken then 18 | 19 | Sum = 2+3 = 5. 20 | Example 2: 21 | Input: 22 | N = 3 23 | Arr = [5, 2, 1] 24 | Output: 25 | 0 1 2 3 5 6 7 8 26 | Your Task: 27 | You don't need to read input or print anything. Your task is to complete the function subsetSum() which takes a list/vector and an integer N as an input parameter and return the list/vector of all the subset sums in increasing order. 28 | 29 | Expected Time Complexity: O(2N) 30 | Expected Auxiliary Space: O(2N) 31 | 32 | Constraints: 33 | 1 <= N <= 15 34 | 0 <= Arr[i] <= 10000 35 | */ 36 | 37 | void dfs(vector &arr, int i, vector &ans, int stn) 38 | { 39 | if (i == arr.size()) 40 | { 41 | ans.push_back(stn); 42 | return; 43 | } 44 | 45 | dfs(arr, i + 1, ans, stn); 46 | dfs(arr, i + 1, ans, stn + arr[i]); 47 | } 48 | 49 | vector subsetSums(vector arr, int N) 50 | { 51 | vector ans; 52 | dfs(arr, 0, ans, 0); 53 | sort(ans.begin(), ans.end()); 54 | return ans; 55 | } 56 | -------------------------------------------------------------------------------- /Striver Sheet/Day-9/Subsets II.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Subsets II 3 | ========== 4 | 5 | Given an integer array nums that may contain duplicates, return all possible subsets (the power set). 6 | 7 | The solution set must not contain duplicate subsets. Return the solution in any order. 8 | 9 | Example 1: 10 | Input: nums = [1,2,2] 11 | Output: [[],[1],[1,2],[1,2,2],[2],[2,2]] 12 | 13 | Example 2: 14 | Input: nums = [0] 15 | Output: [[],[0]] 16 | 17 | Constraints: 18 | 1 <= nums.length <= 10 19 | -10 <= nums[i] <= 10 20 | */ 21 | 22 | class Solution 23 | { 24 | public: 25 | void dfs(vector &nums, int i, vector atn, vector> &ans) 26 | { 27 | ans.push_back(atn); 28 | for (int j = i; j < nums.size(); ++j) 29 | { 30 | if (j != i && nums[j] == nums[j - 1]) 31 | continue; 32 | atn.push_back(nums[j]); 33 | dfs(nums, j + 1, atn, ans); 34 | atn.pop_back(); 35 | } 36 | } 37 | 38 | vector> subsetsWithDup(vector &nums) 39 | { 40 | sort(nums.begin(), nums.end()); 41 | vector> ans; 42 | dfs(nums, 0, {}, ans); 43 | return ans; 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-cayman --------------------------------------------------------------------------------