├── Array ├── 1074. Number of Submatrices That Sum to Target.cpp ├── 118-Pascal's-Triangle.cpp ├── 121. Best Time to Buy and Sell Stock.cpp ├── 1266. Minimum Time Visiting All Points.cpp ├── 1287. Element Appearing More Than 25% In Sorted Array.cpp ├── 1299. Replace Elements with Greatest Element on Right Side.cpp ├── 1464. Maximum Product of Two Elements in an Array.cpp ├── 15. 3Sum.cpp ├── 1539. Kth Missing Positive Number.cpp ├── 1561. Maximum Number of Coins You Can Get.cpp ├── 1630. Arithmetic Subarrays.cpp ├── 1637. Widest Vertical Area Between Two Points Containing No Points.cpp ├── 1688. Count of Matches in Tournament.cpp ├── 1700. Number of Students Unable to Eat Lunch.cpp ├── 1716. Calculate Money in Leetcode Bank.cpp ├── 1727. Largest Submatrix With Rearrangements.cpp ├── 1732. Find the Highest Altitude.cpp ├── 1752. Check if Array Is Sorted and Rotated.cpp ├── 1814. Count Nice Pairs in an Array.cpp ├── 1887. Reduction Operations to Make the Array Elements Equal.cpp ├── 189. Rotate Array.cpp ├── 1913. Maximum Product Difference Between Two Pairs.cpp ├── 1921. Eliminate Maximum Number of Monsters.cpp ├── 2009. Minimum Number of Operations to Make Array Continuous.cpp ├── 2016. Maximum Difference Between Increasing Elements.cpp ├── 2073. Time Needed to Buy Tickets.cpp ├── 2149. Rearrange Array Elements by Sign.cpp ├── 217. Contains Duplicate.cpp ├── 2251. Number of Flowers in Full Bloom.cpp ├── 229. Majority Element II.cpp ├── 239. Sliding Window Maximum.cpp ├── 2402. Meeting Rooms III.cpp ├── 2405. Optimal Partition of String.cpp ├── 26. Remove Duplicates from Sorted Array.cpp ├── 268. Missing Number.cpp ├── 27. Remove Element.cpp ├── 2706. Buy Two Chocolates.cpp ├── 283. Move Zeroes.cpp ├── 287. Find the Duplicate Number.cpp ├── 2966. Divide Array Into Arrays With Max Difference.cpp ├── 34. Find First and Last Position of Element in Sorted Array.cpp ├── 35. Search Insert Position.cpp ├── 368. Largest Divisible Subset.cpp ├── 4. Median of Two Sorted Arrays.cpp ├── 41. First Missing Positive.cpp ├── 442. Find All Duplicates in an Array.cpp ├── 506. Relative Ranks.cpp ├── 525. Contiguous Array.cpp ├── 53-Maximum-Subarray.cpp ├── 57. Insert Interval.cpp ├── 645. Set Mismatch.cpp ├── 66. Plus One.cpp ├── 6954. Count Pairs Whose Sum is Less than Target.cpp ├── 73-Set-Matrix-Zeroes.cpp ├── 75-Sort-Colors.cpp ├── 881. Boats to Save People.cpp ├── 896. Monotonic Array.cpp ├── 905. Sort Array By Parity.cpp ├── 977. Squares of a Sorted Array.cpp ├── 997. Find the Town Judge.cpp ├── Array insert at end.cpp ├── Array insert at index.cpp ├── C++ Array (print an element) | Set 2.cpp ├── C++ Arrays (Sum of array) | Set 1.cpp ├── Check if array is sorted.cpp ├── Check if two arrays are equal or not.cpp ├── Common elements.cpp ├── Convert-array-into-Zig-Zag-fashion.cpp ├── Count Odd Even.cpp ├── Cumulative frequency of count of each element in an unsorted array.cpp ├── Display-longest-name.cpp ├── Find duplicates in an array.cpp ├── Find the Frequency.cpp ├── Find triplets with zero sum.cpp ├── Find-minimum-and-maximum-element-in-an-array.cpp ├── Fitting-The-Array.cpp ├── Frequencies of Limited Range Array Elements.cpp ├── Frequency In A Sorted Array.cpp ├── Largest Element in the Array.cpp ├── Largest-Element-in-Array.cpp ├── Leaders in an array.cpp ├── Left Rotate an Array by One.cpp ├── Mean And Median of Array.cpp ├── Move all zeroes to end of array.cpp ├── Ninja And The Sorted Check.cpp ├── Perfect-Arrays.cpp ├── Print-Elements-of-Array.cpp ├── Rearrange Array Alternately.cpp ├── Remove Duplicates from Sorted Array.cpp ├── Remove duplicate elements from sorted Array.cpp ├── Reverse sub array.cpp ├── Reverse-an-Array.cpp ├── Rope-Cutting.cpp ├── Rotate Array.cpp ├── Rotate array.cpp ├── Rotation.cpp ├── Second largest element in the array.cpp ├── Second-Largest.cpp ├── Sort 0 1 2.cpp ├── Sort-an-array-of-0s-1s-and-2s.cpp ├── Sum Of Two Arrays.cpp ├── Sum-of-Array.cpp └── Triplet-Sum-in-Array.cpp ├── Backtracking └── 79. Word Search.cpp ├── Bit Magic ├── 136-Single-Number.cpp ├── 1611. Minimum One Bit Operations to Make Integers Zero.cpp ├── 191. Number of 1 Bits.cpp ├── 201. Bitwise AND of Numbers Range.cpp ├── 231-Power-of-Two.cpp ├── Check-whether-K-th-bit-is-set-or-not .cpp ├── Count-total-set-bits.cpp ├── Find-the-element-that-appears-once.cpp ├── Number-of-1-Bits.cpp ├── Power-Set.cpp ├── Power-of-2.cpp └── Two-numbers-with-odd-occurrences.cpp ├── Cpp-STL ├── Find the Frequency.cpp ├── README.md ├── Set-1-(vector).cpp ├── Set-2-(pair).cpp ├── Set-3-(map).cpp └── stl.cpp ├── DP ├── 1043. Partition Array for Maximum Sum.cpp ├── 1143. Longest Common Subsequence.cpp ├── 1155. Number of Dice Rolls With Target Sum.cpp ├── 119. Pascal's Triangle II.cpp ├── 1335. Minimum Difficulty of a Job Schedule.cpp ├── 1578. Minimum Time to Make Rope Colorful.cpp ├── 198. House Robber.cpp ├── 279. Perfect Squares.cpp ├── 300. Longest Increasing Subsequence.cpp ├── 509. Fibonacci Number.cpp ├── 629. K Inverse Pairs Array.cpp ├── 70. Climbing Stairs.cpp ├── 746. Min Cost Climbing Stairs.cpp ├── 85. Maximal Rectangle.cpp ├── 91. Decode Ways.cpp ├── Count ways to reach the n'th stair.cpp ├── Get Minimum Squares.cpp └── Minimum steps to minimize n as per given condition.cpp ├── Graph ├── 2092. Find All People With Secret.cpp ├── 547. Number of Provinces.cpp ├── 787. Cheapest Flights Within K Stops.cpp └── Number of Provinces.cpp ├── Greedy ├── 1877. Minimize Maximum Pair Sum in Array.cpp ├── 2971. Find Polygon With the Largest Perimeter.cpp ├── 452. Minimum Number of Arrows to Burst Balloons.cpp ├── 455. Assign Cookies.cpp ├── 575. Distribute Candies.cpp ├── 678. Valid Parenthesis String.cpp ├── Check if it is possible to survive on Island.cpp ├── Chocolate Distribution Problem.cpp ├── Minimum Cost of ropes.cpp ├── N meetings in one room.cpp ├── Reverse words in a given string.cpp └── Shop in Candy Store.cpp ├── Hashing ├── 1436. Destination City.cpp ├── 49. Group Anagrams.cpp ├── Find the Frequency.cpp └── Frequency In A Sorted Array.cpp ├── Hashmap ├── 1481. Least Number of Unique Integers after K Removals.cpp ├── 1496. Path Crossing.cpp ├── 2391. Minimum Amount of Time to Collect Garbage.cpp ├── 26. Remove Duplicates from Sorted Array.cpp └── 2870. Minimum Number of Operations to Make Array Empty.cpp ├── Heap ├── 2353. Design a Food Rating System.cpp ├── Buy the ticket.cpp ├── Check Max-Heap.cpp ├── Kth largest element.cpp ├── Merge K sorted arrays.cpp └── Running Median.cpp ├── Linked List ├── 1019. Next Greater Node In Linked List.cpp ├── 141. Linked List Cycle.cpp ├── 142. Linked List Cycle II.cpp ├── 146. LRU Cache.cpp ├── 160. Intersection of Two Linked Lists.cpp ├── 1721. Swapping Nodes in a Linked List.cpp ├── 19. Remove Nth Node From End of List.cpp ├── 206. Reverse Linked List.cpp ├── 2095. Delete the Middle Node of a Linked List.cpp ├── 234. Palindrome Linked List.cpp ├── 237. Delete Node in a Linked List.cpp ├── 82. Remove Duplicates from Sorted List II.cpp ├── 83. Remove Duplicates from Sorted List.cpp ├── 876. Middle of the Linked List.cpp ├── Bubble Sort (Iterative) Linked List.cpp ├── Check if Linked List is Palindrome.cpp ├── Code : Reverse LL (Recursive).cpp ├── Code: Merge Two Sorted LL.cpp ├── Code: Midpoint of LL.cpp ├── Code: Reverse LL (Iterative).cpp ├── Count nodes of linked list.cpp ├── Delete Middle of Linked List.cpp ├── Delete a Node in Single Linked List.cpp ├── Delete every N nodes.cpp ├── Delete node.cpp ├── Delete nodes having greater value on right.cpp ├── Delete without head pointer.cpp ├── Detect Loop in linked list.cpp ├── Eliminate Duplicates.cpp ├── Even after Odd Linked List.cpp ├── Find a Node in LL (recursive).cpp ├── Find a Node in Linked List.cpp ├── Find the first node of loop in linked list.cpp ├── Finding middle element in a linked list.cpp ├── Given a linked list of 0s, 1s and 2s, sort it.cpp ├── Insert node (recursive).cpp ├── Length of Linked List.cpp ├── Linked List Insertion.cpp ├── Linked List Length Even or Odd.cpp ├── Merge Sort for Linked List.cpp ├── Next Greater Element.cpp ├── Node at a given index in linked list.cpp ├── Nth node from end of linked list.cpp ├── Palindrome Linked List.cpp ├── Print Reversed Linked List.cpp ├── Print ith node.cpp ├── Remove duplicate element from sorted Linked List.cpp ├── Remove duplicates from an unsorted linked list.cpp ├── Reverse Linked List.cpp ├── Reverse a linked list.cpp ├── Search in Linked List.cpp ├── Swap Two Nodes of Linked List.cpp └── kReverse.cpp ├── Priority Queue ├── 1464. Maximum Product of Two Elements in an Array.cpp ├── 1642. Furthest Building You Can Reach.cpp ├── Code : Max Priority Queue.cpp └── Code : Remove Min.cpp ├── Queue ├── 232. Implement Queue using Stacks.cpp ├── 239. Sliding Window Maximum.cpp ├── 950. Reveal Cards In Increasing Order.cpp ├── Check redundant brackets.cpp ├── Code : Queue Using LL.cpp ├── Maximum of all subarrays of size k.cpp ├── Queue Reversal.cpp └── Reverse Queue.cpp ├── README.md ├── Recursion ├── 231. Power of Two.cpp ├── 509-Fibonacci-Number.cpp ├── 78-Subsets.cpp ├── Factorial.cpp ├── Josephus-problem.cpp ├── Nth-Fibonacci-Number.cpp ├── Print-1-To-N-Without-Loop.cpp ├── Print-1-to-n-without-using-loops.cpp ├── Subsets.cpp ├── The-Nth-Fibonnaci.cpp └── Tower-Of-Hanoi.cpp ├── Searching ├── 1351. Count Negative Numbers in a Sorted Matrix.cpp ├── 278. First Bad Version.cpp ├── 33-Search-in-Rotated-Sorted-Array.cpp ├── 34. Find First and Last Position of Element in Sorted Array.cpp ├── 35. Search Insert Position.cpp ├── 4-Median-of-Two-Sorted-Arrays.cpp ├── 540-Single-Element-in-a-Sorted-Array.cpp ├── 69-Sqrt(x).cpp ├── 704. Binary Search.cpp ├── 744. Find Smallest Letter Greater Than Target.cpp ├── Aggressive Cows.cpp ├── Find-the-element-that-appears-once-in-sorted-array.cpp ├── First-and-last-occurrences-of-x.cpp ├── Index-of-first-1-in-a-sorted-array-of-0s-and-1s.cpp ├── Left-most-and-right-most-index.cpp ├── Median-of-2-Sorted-Arrays-of-Different-Sizes.cpp ├── Peak-element.cpp ├── Search-an-Element-in-an-array.cpp ├── Search-an-element-in-sorted-and-rotated-array.cpp ├── Searching-an-element-in-a-sorted-array.cpp └── Square-root-of-a-number.cpp ├── Sliding Window ├── 1838. Frequency of the Most Frequent Element.cpp ├── 2444. Count Subarrays With Fixed Bounds.cpp └── 713. Subarray Product Less Than K.cpp ├── Sorting ├── 217. Contains Duplicate.cpp ├── Sort String.cpp ├── Sort The Array.cpp └── Sort an array of 0s, 1s and 2s.cpp ├── Stack ├── 1249. Minimum Remove to Make Valid Parentheses.cpp ├── 150. Evaluate Reverse Polish Notation.cpp ├── 155. Min Stack.cpp ├── 20. Valid Parentheses.cpp ├── 225. Implement Stack using Queues.cpp ├── 341. Flatten Nested List Iterator.cpp ├── 402. Remove K Digits.cpp ├── 456. 132 Pattern.cpp ├── 496. Next Greater Element I.cpp ├── 739. Daily Temperatures.cpp ├── 901. Online Stock Span.cpp ├── Code : Balanced Parenthesis.cpp ├── Code : Stack Using LL ├── Implement Stack using Linked List.cpp ├── Implement stack using array.cpp ├── Parenthesis Checker.cpp ├── Reverse a Stack Using Recursion.cpp ├── Reverse a Stack.cpp ├── Sort a Stack.cpp ├── Stack Implementation Using Array.cpp ├── Stock span problem.cpp └── The Celebrity Problem.cpp ├── String ├── 1160. Find Words That Can Be Formed by Characters.cpp ├── 13. Roman to Integer.cpp ├── 14. Longest Common Prefix.cpp ├── 1422. Maximum Score After Splitting a String.cpp ├── 1531. String Compression II.cpp ├── 1544. Make The String Great.cpp ├── 1614. Maximum Nesting Depth of the Parentheses.cpp ├── 1624. Largest Substring Between Two Equal Characters.cpp ├── 1662. Check If Two String Arrays are Equivalent.cpp ├── 168. Excel Sheet Column Title.cpp ├── 1704. Determine if String Halves Are Alike ├── 1758. Minimum Changes To Make Alternating Binary String.cpp ├── 1759. Count Number of Homogenous Substrings.cpp ├── 1897. Redistribute Characters to Make All Strings Equal.cpp ├── 1903. Largest Odd Number in String.cpp ├── 1930. Unique Length-3 Palindromic Subsequences.cpp ├── 205. Isomorphic Strings.cpp ├── 2108. Find First Palindromic String in the Array.cpp ├── 2264. Largest 3-Same-Digit Number in String.cpp ├── 242. Valid Anagram.cpp ├── 2707. Extra Characters in a String.cpp ├── 2785. Sort Vowels in a String.cpp ├── 28. Find the Index of the First Occurrence in a String.cpp ├── 344-Reverse-String.cpp ├── 387. First Unique Character in a String.cpp ├── 389. Find the Difference.cpp ├── 392. Is Subsequence.cpp ├── 451. Sort Characters By Frequency.cpp ├── 49. Group Anagrams.cpp ├── 58. Length of Last Word.cpp ├── 647. Palindromic Substrings.cpp ├── 76. Minimum Window Substring.cpp ├── C++ Strings.cpp ├── Count the characters.cpp ├── Display-longest-name.cpp ├── Palindrome-String.cpp ├── Remove Spaces.cpp ├── Replace Spaces.cpp ├── Reverse a String.cpp ├── Reverse-a-String.cpp ├── Sort String.cpp └── String comparison.cpp ├── Tree ├── 100. Same Tree.cpp ├── 101. Symmetric Tree.cpp ├── 102. Binary Tree Level Order Traversal.cpp ├── 104. Maximum Depth of Binary Tree.cpp ├── 106. Construct Binary Tree from Inorder and Postorder Traversal.cpp ├── 108. Convert Sorted Array to Binary Search Tree.cpp ├── 110. Balanced Binary Tree.cpp ├── 111. Minimum Depth of Binary Tree.cpp ├── 112. Path Sum.cpp ├── 144-Binary-Tree-Preorder-Traversal.cpp ├── 145-Binary-Tree-Postorder-Traversal.cpp ├── 1457. Pseudo-Palindromic Paths in a Binary Tree.cpp ├── 1609. Even Odd Tree.cpp ├── 199-Binary-Tree-Right-Side-View.cpp ├── 222. Count Complete Tree Nodes.cpp ├── 226. Invert Binary Tree.cpp ├── 404. Sum of Left Leaves.cpp ├── 513. Find Bottom Left Tree Value.cpp ├── 543. Diameter of Binary Tree.cpp ├── 606. Construct String from Binary Tree.cpp ├── 623. Add One Row to Tree.cpp ├── 700. Search in a Binary Search Tree.cpp ├── 872. Leaf-Similar Trees.cpp ├── 938. Range Sum of BST.cpp ├── 94-Binary-Tree-Inorder-Traversal.cpp ├── 958. Check Completeness of a Binary Tree.cpp ├── 98. Validate Binary Search Tree.cpp ├── 988. Smallest String Starting From Leaf.cpp ├── Array to BST.cpp ├── Check for BST.cpp ├── Check if Tree is Isomorphic.cpp ├── Code : Count leaf nodes.cpp ├── Code : Find a node.cpp ├── Code : Find height.cpp ├── Code : Find sum of nodes.cpp ├── Code : Height of Binary Tree.cpp ├── Code : Max data node.cpp ├── Code : Mirror.cpp ├── Code : PostOrder Traversal.cpp ├── Code: BST to Sorted LL.cpp ├── Code: Construct BST from a Sorted Array.cpp ├── Code: Print Elements in Range.cpp ├── Code: Search in BST.cpp ├── Complete Binary Tree.cpp ├── Contains x.cpp ├── Count Leaves in Binary Tree.cpp ├── Count Number of Nodes in a Binary Tree.cpp ├── Count nodes.cpp ├── Determine if Two Trees are Identical.cpp ├── Find Path in BST.cpp ├── Height of Binary Tree.cpp ├── Inorder-Traversal.cpp ├── Level order traversal.cpp ├── Max and min element in Binary Tree.cpp ├── Mirror Tree.cpp ├── Next larger.cpp ├── Node with maximum child sum.cpp ├── Postorder-Traversal.cpp ├── Preorder-Traversal.cpp ├── Print Level Wise.cpp ├── Replace with depth.cpp ├── Right-View-of-Binary-Tree.cpp ├── Search a node in BST.cpp ├── Size of Binary Tree.cpp ├── Structurally identical.cpp ├── Sum of Binary Tree.cpp ├── Sum of Leaf Nodes.cpp └── Symmetric Tree.cpp ├── Trie └── 208. Implement Trie(Prefix Tree).cpp ├── Two Pointer ├── 1512. Number of Good Pairs.cpp ├── 1658. Minimum Operations to Reduce X to Zero.cpp ├── 42. Trapping Rain Water.cpp ├── 844. Backspace String Compare.cpp ├── 948. Bag of Tokens.cpp └── 977. Squares of a Sorted Array.cpp ├── mathematics ├── 1-Absolute-Value.cpp ├── 1291. Sequential Digits.cpp ├── 1342. Number of Steps to Reduce a Number to Zero.cpp ├── 172-Factorial-Trailing-Zeroes.cpp ├── 204-Count-Primes.cpp ├── 231. Power of Two.cpp ├── 2485. Find the Pivot Integer.cpp ├── 279. Perfect Squares.cpp ├── 326. Power of Three.cpp ├── 342. Power of Four.cpp ├── 343. Integer Break.cpp ├── 50-Pow(x, n).cpp ├── 7. Reverse Integer ├── 70. Climbing Stairs.cpp ├── 9-Palindrome-Number.cpp ├── Addition Under Modulo.cpp ├── Convert Celsius To Fahrenheit.cpp ├── Count ways to reach the n'th stair.cpp ├── Count-Odd-Factors.cpp ├── Digits In Factorial.cpp ├── Factorial.cpp ├── Find the median.cpp ├── GCD-of-two-numbers.cpp ├── GP Term.cpp ├── Get Minimum Squares.cpp ├── Multiplication Under Modulo.cpp ├── Natural-Sum.cpp ├── Number-of-divisors.cpp ├── Odd-or-Even.cpp ├── Palindrome.cpp ├── Power-Of-Numbers.cpp ├── Primality Test.cpp ├── Prime-Number.cpp ├── Sum of primes.cpp ├── Sum-Of-Digits.cpp ├── Sum-of-fifth-powers-of-the-first-n-natural-numbers.cpp ├── Sum-of-first-n-terms.cpp └── Trailing-zeroes-in-factorial.cpp └── matrix ├── 1463. Cherry Pickup II.cpp ├── 1582. Special Positions in a Binary Matrix.cpp ├── 1992. Find All Groups of Farmland.cpp ├── 2482. Difference Between Ones and Zeros in Row and Column.cpp ├── 463. Island Perimeter.cpp ├── 661. Image Smoother.cpp └── 867. Transpose Matrix.cpp /Array/118-Pascal's-Triangle.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> generate(int numRows) { 4 | vector> r(numRows); 5 | 6 | for(int i = 0; i < numRows; i++) { 7 | r[i].resize(i+1); 8 | r[i][0] = r[i][i] = 1; 9 | 10 | for(int j = 1; j < i; j++) 11 | r[i][j] = r[i-1][j - 1] + r[i - 1][j]; 12 | } 13 | return r; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Array/121. Best Time to Buy and Sell Stock.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector& prices) { 4 | int maxPro = 0; 5 | int minPrice = INT_MAX; 6 | for(int i = 0; i < prices.size(); i++) { 7 | minPrice = min(minPrice, prices[i]); 8 | maxPro = max(maxPro, prices[i]- minPrice); 9 | } 10 | return maxPro; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /Array/1266. Minimum Time Visiting All Points.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int toTime(std::vector& from, std::vector& to) { 4 | int xDiff = std::abs(from[0] - to[0]); 5 | int yDiff = std::abs(from[1] - to[1]); 6 | 7 | return std::max(xDiff, yDiff); 8 | } 9 | 10 | int minTimeToVisitAllPoints(vector>& points) { 11 | int time = 0; 12 | 13 | for (int i = 1; i < points.size(); i++) { 14 | time += toTime(points[i - 1], points[i]); 15 | } 16 | 17 | return time; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Array/1287. Element Appearing More Than 25% In Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findSpecialInteger(vector& arr) { 4 | int n = arr.size(); 5 | int quarter = n / 4; 6 | for(int i = 0; i < n; i++) { 7 | if(arr[i] == arr[i + quarter]) 8 | return arr[i]; 9 | } 10 | return -1; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /Array/1299. Replace Elements with Greatest Element on Right Side.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector replaceElements(vector& arr) { 4 | int n = arr.size(); 5 | vector ans; 6 | int mx = arr[n-1]; 7 | ans.push_back(-1); 8 | for(int i=n-2;i>=0;i--){ 9 | ans.push_back(mx); 10 | if(arr[i]>=mx){ 11 | 12 | mx = arr[i]; 13 | } 14 | } 15 | reverse(ans.begin(),ans.end()); 16 | return ans; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Array/1464. Maximum Product of Two Elements in an Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProduct(vector& nums) { 4 | int result = 0; 5 | int current = 0; 6 | for(int i = 0; i < nums.size(); i++) { 7 | for(int j = i + 1; j < nums.size(); j++) { 8 | current = (nums[i] - 1) * (nums[j] - 1); 9 | result = max(current, result); 10 | } 11 | } 12 | return result; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Array/1539. Kth Missing Positive Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findKthPositive(vector& arr, int k) { 4 | if(arr[0] > k) return k; 5 | int current = k; 6 | for(int a:arr) { 7 | if(a <= current){ 8 | current++; 9 | }else { 10 | break; 11 | } 12 | } 13 | return current; 14 | } 15 | }; 16 | 17 | -------------------------------------------------------------------------------- /Array/1561. Maximum Number of Coins You Can Get.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxCoins(vector& piles) { 4 | int n = piles.size(); 5 | sort(piles.begin(), piles.end()); 6 | int start = n - 2; 7 | int end = n / 3; 8 | int myCoins = 0; 9 | while(start >= end) { 10 | myCoins += piles[start]; 11 | start = start - 2; 12 | } 13 | return myCoins; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Array/1637. Widest Vertical Area Between Two Points Containing No Points.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxWidthOfVerticalArea(vector>& points) { 4 | vector xSorted; 5 | for (const auto& point : points) { 6 | xSorted.push_back(point[0]); 7 | } 8 | 9 | sort(xSorted.begin(), xSorted.end()); 10 | 11 | int maxWidth = 0; 12 | for (int i = 0; i < xSorted.size() - 1; i++) { 13 | maxWidth = max(maxWidth, xSorted[i + 1] - xSorted[i]); 14 | } 15 | 16 | return maxWidth; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Array/1688. Count of Matches in Tournament.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numberOfMatches(int n) { 4 | if (n == 1) return 0; 5 | if(n % 2 == 0) 6 | return n / 2 + numberOfMatches(n / 2); 7 | else 8 | return (n - 1) / 2 + numberOfMatches((n - 1) / 2 + 1); 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /Array/1700. Number of Students Unable to Eat Lunch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int countStudents(vector& students, vector& sandwiches) { 7 | vector counts(2, 0); 8 | for (int student : students) 9 | counts[student]++; 10 | 11 | int remaining = sandwiches.size(); 12 | for (int sandwich : sandwiches) { 13 | if (counts[sandwich] == 0) 14 | break; 15 | if (remaining == 0) 16 | break; 17 | counts[sandwich]--; 18 | remaining--; 19 | } 20 | 21 | return remaining; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Array/1716. Calculate Money in Leetcode Bank.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int totalMoney(int n) { 4 | int w = n / 7; 5 | int money = w * 28; 6 | money += (7 * w * (w - 1)) / 2; 7 | 8 | if (n % 7) { 9 | int extra_days = n % 7; 10 | int money_to_add = w + 1; 11 | for (int i = 0; i < extra_days; ++i) { 12 | money += money_to_add; 13 | money_to_add += 1; 14 | } 15 | } 16 | return money; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Array/1727. Largest Submatrix With Rearrangements.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int largestSubmatrix(vector>& matrix) { 4 | int m = matrix.size(), n = matrix[0].size(); 5 | int ans = 0; 6 | for (int row = 0; row 0){ 9 | matrix[row][col] += matrix[row-1][col]; 10 | } 11 | } 12 | 13 | vector currRow = matrix[row]; 14 | sort(currRow.begin(), currRow.end(), greater()); 15 | for(int i=0; i& gain) { 4 | int highestAltitude = 0; 5 | int currentAltitude = 0; 6 | 7 | for(int i = 0; i < gain.size(); i++) { 8 | currentAltitude += gain[i]; 9 | highestAltitude = max(highestAltitude, currentAltitude); 10 | } 11 | 12 | return highestAltitude; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Array/1752. Check if Array Is Sorted and Rotated.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool check(vector& nums) { 4 | int n =nums.size(); 5 | int count = 0; 6 | for(int i = 0; i < n; i++) { 7 | if(nums[i] > nums[(i+1) % n]) 8 | count++; 9 | } 10 | if(count > 1) return false; 11 | return true; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Array/1814. Count Nice Pairs in an Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countNicePairs(vector& nums) { 4 | const int MOD = 1e9 + 7; 5 | int n = nums.size(); 6 | std::unordered_map frequency; 7 | 8 | long long count = 0; 9 | 10 | for (int i = 0; i < n; ++i) { 11 | int diff = nums[i] - reverseNum(nums[i]); 12 | count = (count + frequency[diff]) % MOD; 13 | frequency[diff]++; 14 | } 15 | 16 | return count; 17 | } 18 | 19 | private: 20 | int reverseNum(int num) { 21 | int reversed = 0; 22 | while(num > 0) { 23 | reversed = reversed * 10 + num % 10; 24 | num /= 10; 25 | } 26 | return reversed; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Array/1887. Reduction Operations to Make the Array Elements Equal.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int reductionOperations(vector& nums) { 4 | sort(nums.begin(), nums.end()); 5 | int size = nums.size(); 6 | int ans = 0; 7 | for (int i = size - 1; i > 0; --i) { 8 | if (nums[i - 1] != nums[i]) { 9 | ans += size - i; 10 | } 11 | } 12 | return ans; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Array/189. Rotate Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void rotate(vector& nums, int k) { 4 | 5 | vectortemp(nums.size()); 6 | 7 | for(int i = 0; i < nums.size(); i++) { 8 | temp[(i+k) % nums.size()] = nums[i]; 9 | } 10 | 11 | nums = temp; 12 | 13 | // Time Complexity => O(N) 14 | // Space Complexity => O(1) 15 | // k %= nums.size(); 16 | // reverse(nums.begin(), nums.end()); 17 | // reverse(nums.begin(), nums.begin() + k); 18 | // reverse(nums.begin() + k, nums.end()); 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Array/1913. Maximum Product Difference Between Two Pairs.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProductDifference(vector& nums) { 4 | int n=nums.size(); 5 | sort(nums.begin(), nums.end()); 6 | return ((nums[n-1]*nums[n-2])-(nums[0]*nums[1])); 7 | } 8 | }; 9 | -------------------------------------------------------------------------------- /Array/1921. Eliminate Maximum Number of Monsters.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int eliminateMaximum(vector& dist, vector& speed) { 4 | vectortime; 5 | for(int i = 0; i < speed.size(); i++) { 6 | time.push_back((double)dist[i]/(double)speed[i]); 7 | } 8 | sort(time.begin(), time.end()); 9 | int t = 0, ans = 0; 10 | for(auto a : time) { 11 | if(a <= t) { 12 | break; 13 | } 14 | else { 15 | ans++; 16 | t++; 17 | } 18 | } 19 | return ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Array/2009. Minimum Number of Operations to Make Array Continuous.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minOperations(vector& nums) { 4 | int n = nums.size(); 5 | std::sort(nums.begin(), nums.end()); 6 | std::vector uniqueNums(nums.begin(), std::unique(nums.begin(), nums.end())); 7 | int ans = std::numeric_limits::max(); 8 | 9 | for (int i = 0; i < uniqueNums.size(); ++i) { 10 | int s = uniqueNums[i]; 11 | int e = s + n - 1; 12 | auto it = std::upper_bound(uniqueNums.begin(), uniqueNums.end(), e); 13 | 14 | int idx = std::distance(uniqueNums.begin(), it); 15 | ans = std::min(ans, n - (idx - i)); 16 | } 17 | return ans; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Array/2016. Maximum Difference Between Increasing Elements.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maximumDifference(vector& nums) { 4 | int res=-1; 5 | int minEle=INT_MAX; 6 | for(int i=0; i& tickets, int k) { 4 | int total = 0; 5 | 6 | for (int i = 0; i < tickets.size(); ++i) { 7 | if (i <= k) { 8 | total += min(tickets[i], tickets[k]); 9 | } else { 10 | total += min(tickets[i], tickets[k] - 1); 11 | } 12 | } 13 | 14 | return total; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Array/2149. Rearrange Array Elements by Sign.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector rearrangeArray(vector& nums) { 4 | vector res; 5 | for (int i = 0, j = 0; max(i, j) < nums.size(); ) { 6 | while (nums[i++] < 0); 7 | while (nums[j++] > 0); 8 | res.insert(end(res), {nums[i - 1], nums[j - 1]}); 9 | } 10 | return res; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /Array/2251. Number of Flowers in Full Bloom.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector fullBloomFlowers(vector>& flowers, vector& people) { 4 | vector start, end; 5 | for (auto& t : flowers) 6 | start.push_back(t[0]), end.push_back(t[1]); 7 | sort(start.begin(), start.end()); 8 | sort(end.begin(), end.end()); 9 | vector res; 10 | for (int t : people) { 11 | int started = upper_bound(start.begin(), start.end(), t) - start.begin(); 12 | int ended = lower_bound(end.begin(), end.end(), t) - end.begin(); 13 | res.push_back(started - ended); 14 | } 15 | return res; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Array/229. Majority Element II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector majorityElement(vector& nums) { 4 | int candidate1 = 0, candidate2 = 0, count1 = 0, count2 = 0; 5 | // First pass to find potential candidates 6 | for (auto num : nums) { 7 | if (candidate1 == num) count1++; 8 | else if (candidate2 == num) count2++; 9 | else if (count1 == 0) candidate1 = num, count1 = 1; 10 | else if (count2 == 0) candidate2 = num, count2 = 1; 11 | else count1--, count2--; 12 | } 13 | // Second pass to verify candidates 14 | count1 = count2 = 0; 15 | for (int num : nums) { 16 | if (num == candidate1) count1++; 17 | else if (num == candidate2) count2++; 18 | } 19 | 20 | vector ans; 21 | if (count1 > nums.size() / 3) ans.push_back(candidate1); 22 | if (count2 > nums.size() / 3) ans.push_back(candidate2); 23 | 24 | return ans; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Array/239. Sliding Window Maximum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector maxSlidingWindow(vector& nums, int k) { 4 | vectorresult; 5 | for(int i = 0; i <= nums.size() - k; i++) { 6 | int maxi = nums[i]; 7 | for(int j = i + 1; j < i + k; j++) { 8 | maxi = max(maxi, nums[j]); 9 | } 10 | result.push_back(maxi); 11 | } 12 | return result; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Array/2405. Optimal Partition of String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int partitionString(string s) { 4 | int ans = 1; 5 | setst; 6 | for(auto c : s) { 7 | if(st.find(c) != st.end()) { 8 | st.clear(); 9 | ans++; 10 | } 11 | st.insert(c); 12 | } 13 | return ans; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Array/26. Remove Duplicates from Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int removeDuplicates(vector& nums) { 4 | // T.C => O(N) 5 | // S.C. => O(N) 6 | // int n = nums.size(); 7 | // int temp[n]; 8 | // temp[0] = nums[0]; 9 | // int res = 1; 10 | 11 | // for(int i = 1; i < n; i++){ 12 | // if(temp[res - 1] != nums[i]){ 13 | // temp[res] = nums[i]; 14 | // res++; 15 | // } 16 | // } 17 | // for(int i = 0; i < n; i++){ 18 | // nums[i] = temp[i]; 19 | // } 20 | // return res; 21 | 22 | //==================================================// 23 | 24 | // T.C => O(N) 25 | // S.C. => O(1) 26 | int n = nums.size(); 27 | int res = 1; 28 | for(int i = 1; i < n; i++){ 29 | if(nums[res-1] != nums[i]){ 30 | nums[res] = nums[i]; 31 | res++; 32 | } 33 | } 34 | return res; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /Array/268. Missing Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int missingNumber(vector& nums) { 4 | int sizeofArray = nums.size(); 5 | int sizeofElements = sizeofArray * (sizeofArray + 1) / 2; 6 | int sumofArray = 0; 7 | for(int i = 0; i < nums.size(); i++) { 8 | sumofArray += nums[i]; 9 | } 10 | return sizeofElements - sumofArray; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /Array/27. Remove Element.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int removeElement(vector& nums, int val) { 4 | int k = 0; 5 | for(int i = 0; i < nums.size(); i++) { 6 | if(nums[i] != val) { 7 | nums[k++] = nums[i]; 8 | } 9 | } 10 | return k; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /Array/2706. Buy Two Chocolates.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int buyChoco(vector& prices, int money) { 4 | sort(prices.begin(), prices.end()); 5 | return (money >= (prices[0] + prices[1])) ? money - (prices[0] + prices[1]) : money; 6 | } 7 | }; 8 | -------------------------------------------------------------------------------- /Array/283. Move Zeroes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void moveZeroes(vector& nums) { 4 | int n = nums.size(); 5 | for(int i = 0; i < n; i++) { 6 | if(nums[i] == 0){ 7 | for(int j = n-1; j > i; j--){ 8 | if(nums[j] != 0) 9 | swap(nums[i], nums[j]); 10 | } 11 | } 12 | } 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Array/287. Find the Duplicate Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findDuplicate(vector& nums) { 4 | sort(nums.begin(), nums.end()); 5 | for(int i = 0; i < nums.size() - 1; i++) { 6 | if(nums[i] == nums[i + 1]) 7 | return nums[i]; 8 | } 9 | return -1; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /Array/2966. Divide Array Into Arrays With Max Difference.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> divideArray(vector& nums, int k) { 4 | int size = nums.size(); 5 | 6 | 7 | sort(nums.begin(), nums.end()); 8 | 9 | vector> result(size / 3, vector(3)); 10 | int groupIndex = 0; 11 | for (int i = 0; i < size; i += 3) { 12 | if (i + 2 < size && nums[i + 2] - nums[i] <= k) { 13 | result[groupIndex] = { nums[i], nums[i + 1], nums[i + 2] }; 14 | groupIndex++; 15 | } 16 | else { 17 | return vector>(); 18 | } 19 | } 20 | return result; 21 | } 22 | }; 23 | 24 | 25 | -------------------------------------------------------------------------------- /Array/34. Find First and Last Position of Element in Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector searchRange(vector& nums, int target) { 4 | int start = -1, end = -1; 5 | 6 | for(int i = 0; i < nums.size(); i++) { 7 | if(nums[i] == target) { 8 | start = i; 9 | break; 10 | } 11 | } 12 | 13 | for(int i = nums.size() - 1; i >= 0; i--) { 14 | if(nums[i] == target) { 15 | end = i; 16 | break; 17 | } 18 | } 19 | 20 | if(start == -1 || end == -1) { 21 | return {-1, -1}; 22 | } 23 | 24 | return {start, end}; 25 | } 26 | 27 | }; 28 | -------------------------------------------------------------------------------- /Array/35. Search Insert Position.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int searchInsert(vector& nums, int target) { 4 | for(int i = 0; i < nums.size(); i++) { 5 | if(nums[i] >= target) { 6 | return i; 7 | } 8 | } 9 | return nums.size(); 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /Array/41. First Missing Positive.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int firstMissingPositive(vector& nums) { 4 | int n= size(nums); 5 | 6 | for(int i=0;i=1 && x<=n && x!=i+1 && nums[x-1]!=x){ 9 | swap(nums[x-1],nums[i]); 10 | x=nums[i]; 11 | } 12 | } 13 | 14 | for(int i=0;i findDuplicates(vector& nums) { 4 | vectorans; 5 | int n=size(nums); 6 | for(int i=0;i findRelativeRanks(vector& score) { 4 | vector>v; 5 | vectorans(score.size()); 6 | for(int i = 0; i < score.size(); i++) { 7 | v.push_back({score[i], i}); 8 | } 9 | sort(v.rbegin(), v.rend()); 10 | 11 | for(int i = 0; i < v.size(); i++) { 12 | if(i == 0) { 13 | ans[v[i].second] = "Gold Medal"; 14 | } 15 | else if(i == 1) { 16 | ans[v[i].second] = "Silver Medal"; 17 | }else if(i == 2) { 18 | ans[v[i].second] = "Bronze Medal"; 19 | }else { 20 | ans[v[i].second] = to_string(i + 1); 21 | } 22 | } 23 | return ans; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Array/525. Contiguous Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMaxLength(vector& nums) { 4 | int n = nums.size(); 5 | unordered_map mp; 6 | int sum = 0; 7 | int subArray_length = 0; 8 | for (int i = 0; i < n; i++) { 9 | sum += nums[i] == 0 ? -1 : 1; 10 | if (sum == 0) { 11 | subArray_length = i + 1; 12 | } else if (mp.find(sum) != mp.end()) { 13 | subArray_length = max(subArray_length, i - mp[sum]); 14 | } else { 15 | mp[sum] = i; 16 | } 17 | } 18 | return subArray_length; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Array/53-Maximum-Subarray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxSubArray(vector& nums) { 4 | int sum = 0; 5 | int maxi = INT_MIN; 6 | for(auto it: nums) { 7 | sum+= it; 8 | maxi = max(sum, maxi); 9 | if(sum < 0) sum = 0; 10 | } 11 | return maxi; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Array/57. Insert Interval.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> insert(vector>& intervals, vector& newInterval) { 4 | const int n = intervals.size(); 5 | vector> ans; 6 | int i = 0; 7 | 8 | while (i < n && intervals[i][1] < newInterval[0]) 9 | ans.push_back(intervals[i++]); 10 | 11 | // Merge overlapping intervals 12 | while (i < n && intervals[i][0] <= newInterval[1]) { 13 | newInterval[0] = min(newInterval[0], intervals[i][0]); 14 | newInterval[1] = max(newInterval[1], intervals[i][1]); 15 | ++i; 16 | } 17 | 18 | ans.push_back(newInterval); 19 | 20 | while (i < n) 21 | ans.push_back(intervals[i++]); 22 | 23 | return ans; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Array/645. Set Mismatch.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findErrorNums(vector& nums) { 4 | int duplicate = -1, missing = -1; 5 | 6 | for(int i = 1; i <= nums.size(); i++) { 7 | int count = 0; 8 | for(int j = 0; j < nums.size(); j++) { 9 | if(nums[j] == i) { 10 | count++; 11 | } 12 | } 13 | if(count == 2) { 14 | duplicate = i; 15 | }else if(count == 0) { 16 | missing = i; 17 | } 18 | } 19 | return {duplicate, missing}; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Array/66. Plus One.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector plusOne(vector& digits) { 4 | int n = digits.size(); 5 | for(int i = n - 1; i >= 0; i--) { 6 | if(i == n - 1) 7 | digits[i]++; 8 | if(digits[i] == 10) { 9 | digits[i] = 0; 10 | if(i != 0) { 11 | digits[i - 1]++; 12 | } 13 | else { 14 | digits.push_back(0); 15 | digits[i] = 1; 16 | } 17 | } 18 | } 19 | return digits; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Array/6954. Count Pairs Whose Sum is Less than Target.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countPairs(vector& nums, int target) { 4 | int n = nums.size(); 5 | sort(nums.begin(), nums.end()); 6 | int count = 0; 7 | int left = 0, right = n - 1; 8 | 9 | while (left < right) { 10 | if (nums[left] + nums[right] < target) { 11 | count += right - left; 12 | left++; 13 | } else { 14 | right--; 15 | } 16 | 17 | } 18 | 19 | return count; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Array/73-Set-Matrix-Zeroes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void setZeroes(vector>& matrix) { 4 | int col0 = 1, rows = matrix.size(), cols = matrix[0].size(); 5 | 6 | for(int i = 0; i < rows; i++) { 7 | if(matrix[i][0] == 0) col0 = 0; 8 | 9 | for(int j = 1; j < cols; j++) 10 | if(matrix[i][j] == 0) 11 | matrix[i][0] = matrix[0][j] = 0; 12 | } 13 | 14 | for(int i = rows - 1; i >= 0; i--) { 15 | for(int j = cols - 1; j >= 1; j--) 16 | if(matrix[i][0] == 0 || matrix[0][j] == 0) 17 | matrix[i][j] = 0; 18 | if(col0 == 0) matrix[i][0] = 0; 19 | } 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Array/75-Sort-Colors.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void sortColors(vector& nums) { 4 | int low = 0; 5 | int mid = 0; 6 | int high = nums.size() - 1; 7 | 8 | while(mid <= high) { 9 | switch(nums[mid]) { 10 | case 0: 11 | swap(nums[low++], nums[mid++]); 12 | break; 13 | 14 | case 1: 15 | mid++; 16 | break; 17 | 18 | case 2: 19 | swap(nums[mid], nums[high--]); 20 | break; 21 | } 22 | } 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Array/881. Boats to Save People.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numRescueBoats(vector& people, int limit) { 4 | sort(people.begin(), people.end()); 5 | int i = 0, j = people.size() - 1; 6 | int boat = 0; 7 | while(i <= j) { 8 | if(people[i] + people[j] <= limit) 9 | i++; 10 | j--; 11 | boat++; 12 | } 13 | return boat; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Array/896. Monotonic Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isMonotonic(vector& nums) { 4 | bool increasing = true; 5 | bool decreasing = true; 6 | 7 | for(int i = 1; i < nums.size(); i++) { 8 | if(nums[i] > nums[i - 1]) { 9 | decreasing = false; 10 | } else if(nums[i] < nums[i - 1]) { 11 | increasing = false; 12 | } 13 | if(!increasing && !decreasing) { 14 | return false; 15 | } 16 | } 17 | return true; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Array/905. Sort Array By Parity.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector sortArrayByParity(vector& nums) { 4 | int i = 0, j = 0, n = nums.size(); 5 | while(j < n) { 6 | if(nums[j] % 2 == 0) 7 | swap(nums[i++], nums[j++]); 8 | else j++; 9 | } 10 | return nums; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /Array/977. Squares of a Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector sortedSquares(vector& nums) { 4 | int n = nums.size(); 5 | vectorans; 6 | for(int i = 0; i < n; i++) { 7 | nums[i] = pow(nums[i], 2); 8 | ans.push_back(nums[i]); 9 | } 10 | sort(ans.begin(), ans.end()); 11 | return ans; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Array/997. Find the Town Judge.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findJudge(int N, vector>& trust) { 4 | vector in(N + 1), out(N + 1); 5 | for (auto a : trust) { 6 | ++out[a[0]]; 7 | ++in[a[1]]; 8 | } 9 | for (int i = 1; i <= N; ++i) { 10 | if (in[i] == N - 1 && out[i] == 0) return i; 11 | } 12 | return -1; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Array/C++ Array (print an element) | Set 2.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | class Solution{ 7 | public: 8 | int findElementAtIndex(int a[], int n, int key) 9 | { 10 | // Your code goes here 11 | int res = 0; 12 | for(int i = 0; i < n; i++) { 13 | if(i == key) 14 | res = a[i]; 15 | } 16 | return res; 17 | } 18 | }; 19 | 20 | //{ Driver Code Starts. 21 | 22 | int main() { 23 | int t; 24 | cin >> t; 25 | while (t--) { 26 | int n, key; 27 | cin >> n >> key; 28 | int a[n]; 29 | for (int i = 0; i < n; i++) cin >> a[i]; 30 | Solution ob; 31 | cout << ob.findElementAtIndex(a, n, key) << endl; 32 | } 33 | 34 | return 0; 35 | } 36 | // } Driver Code Ends 37 | -------------------------------------------------------------------------------- /Array/C++ Arrays (Sum of array) | Set 1.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | 7 | class Solution{ 8 | public: 9 | int getSum(int a[], int n) { 10 | // Your code goes here 11 | int sum = 0; 12 | for(int i = 0; i < n; i++) { 13 | sum += a[i]; 14 | } 15 | return sum; 16 | } 17 | }; 18 | 19 | //{ Driver Code Starts. 20 | int main() { 21 | int t; 22 | cin >> t; 23 | while (t--) { 24 | int n; 25 | cin >> n; 26 | int a[n]; 27 | for (int i = 0; i < n; i++) cin >> a[i]; 28 | Solution ob; 29 | cout << ob.getSum(a, n) << endl; 30 | } 31 | 32 | return 0; 33 | } 34 | // } Driver Code Ends 35 | -------------------------------------------------------------------------------- /Array/Cumulative frequency of count of each element in an unsorted array.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | 7 | 8 | class Solution{ 9 | public: 10 | vector countFreq(int a[], int n) 11 | { 12 | // Complete the function 13 | mapm; 14 | vectorans; 15 | for(int i = 0; i < n; i++) { 16 | m[a[i]]++; 17 | } 18 | int sum = 0; 19 | for(auto it:m){ 20 | sum+=it.second; 21 | ans.push_back(sum); 22 | } 23 | return ans; 24 | } 25 | }; 26 | 27 | //{ Driver Code Starts. 28 | int main() 29 | { 30 | int t; 31 | cin>>t; 32 | while(t--) 33 | { 34 | int n,sum=0; 35 | cin>>n; 36 | int arr[n]; 37 | for(int i=0;i>arr[i]; 39 | Solution ob; 40 | vector v; 41 | v = ob.countFreq(arr, n); 42 | for(int i:v) 43 | cout< 5 | using namespace std; 6 | 7 | 8 | // } Driver Code Ends 9 | //User function Template for C++ 10 | 11 | class Solution{ 12 | public: 13 | string longest(string names[], int n) 14 | { 15 | string res = names[0]; 16 | 17 | for(int i = 0; i < n; i++) { 18 | if(names[i].size() > res.size()) 19 | res = names[i]; 20 | } 21 | return res; 22 | } 23 | }; 24 | 25 | //{ Driver Code Starts. 26 | 27 | int main() 28 | { 29 | int t; 30 | cin>>t; 31 | while(t--) 32 | { 33 | int n; 34 | cin>>n; 35 | string names[n]; 36 | 37 | for(int i=0;i>names[i]; 39 | Solution ob; 40 | cout<< ob.longest(names, n) << endl; 41 | } 42 | } 43 | 44 | // } Driver Code Ends 45 | -------------------------------------------------------------------------------- /Array/Find duplicates in an array.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | class Solution{ 7 | public: 8 | vector duplicates(long long arr[], int n) { 9 | // code here 10 | vectorans; 11 | sort(arr, arr + n); 12 | for(int i = 0; i < n; i++) { 13 | if(arr[i] == arr[i - 1] && arr[i] != arr[i + 1]) { 14 | ans.push_back(arr[i - 1]); 15 | } 16 | } 17 | if(ans.size() == 0) 18 | ans.push_back(-1); 19 | return ans; 20 | } 21 | }; 22 | 23 | 24 | //{ Driver Code Starts. 25 | int main() { 26 | int t; 27 | cin >> t; 28 | while (t-- > 0) { 29 | int n; 30 | cin >> n; 31 | long long a[n]; 32 | for (int i = 0; i < n; i++) cin >> a[i]; 33 | Solution obj; 34 | vector ans = obj.duplicates(a, n); 35 | for (int i : ans) cout << i << ' '; 36 | cout << endl; 37 | } 38 | return 0; 39 | } 40 | 41 | // } Driver Code Ends 42 | -------------------------------------------------------------------------------- /Array/Frequency In A Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | int countOccurrences(vector < int > arr, int x) { 2 | // Write your code here. 3 | int n = arr.size(); 4 | int count = 0; 5 | for(int i = 0; i < n; i++) { 6 | if(arr[i] == x) 7 | count++; 8 | } 9 | return count; 10 | } 11 | -------------------------------------------------------------------------------- /Array/Largest Element in the Array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | int largestElement(vector &arr, int n) { 3 | // Write your code here. 4 | // Time Complexity => O(nlogn(n)) 5 | // sort(arr.begin(), arr.end()); 6 | // return arr[n-1]; 7 | 8 | int count = arr[0]; 9 | for(int i = 0; i <= n - 1; i++) { 10 | if(count < arr[i]) { 11 | count = arr[i]; 12 | } 13 | } 14 | return count; 15 | } 16 | -------------------------------------------------------------------------------- /Array/Largest-Element-in-Array.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | //Initial Template for C++ 3 | 4 | #include 5 | using namespace std; 6 | 7 | // } Driver Code Ends 8 | //User function Template for C++ 9 | 10 | class Solution 11 | { 12 | public: 13 | int largest(vector &arr, int n) 14 | { 15 | // sort(arr.begin(), arr.end()); 16 | // return arr[n-1]; 17 | 18 | int res = arr[0]; 19 | 20 | for(int i = 0; i < n; i++) { 21 | if(arr[i] > res){ 22 | res = arr[i]; 23 | } 24 | } 25 | return res; 26 | } 27 | }; 28 | 29 | 30 | //{ Driver Code Starts. 31 | int main() 32 | { 33 | int t; 34 | cin >> t; 35 | while (t--) 36 | { 37 | int n; 38 | cin >> n; 39 | vectorarr(n); 40 | for (int i = 0; i < n; i++) 41 | { 42 | cin >> arr[i]; 43 | } 44 | Solution ob; 45 | cout << ob.largest(arr, n) << "\n"; 46 | } 47 | return 0; 48 | } 49 | 50 | // } Driver Code Ends 51 | -------------------------------------------------------------------------------- /Array/Left Rotate an Array by One.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | vector rotateArray(vector& arr, int n) { 3 | // Write your code here. 4 | int temp = arr[0]; 5 | for(int i = 1; i < n; i++) { 6 | arr[i-1] = arr[i]; 7 | } 8 | arr[n-1] = temp; 9 | return arr; 10 | } 11 | -------------------------------------------------------------------------------- /Array/Move all zeroes to end of array.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | //User function template for C++ 7 | class Solution{ 8 | public: 9 | void pushZerosToEnd(int arr[], int n) { 10 | // code here 11 | int count = 0; 12 | for(int i = 0; i < n; i++) { 13 | if(arr[i] != 0){ 14 | swap(arr[i] , arr[count]); 15 | count++; 16 | } 17 | } 18 | 19 | } 20 | }; 21 | 22 | //{ Driver Code Starts. 23 | int main() { 24 | int t; 25 | cin >> t; 26 | while (t--) { 27 | int n, i; 28 | cin >> n; 29 | int arr[n]; 30 | for (i = 0; i < n; i++) { 31 | cin >> arr[i]; 32 | } 33 | Solution ob; 34 | ob.pushZerosToEnd(arr, n); 35 | for (i = 0; i < n; i++) { 36 | cout << arr[i] << " "; 37 | } 38 | cout << "\n"; 39 | } 40 | return 0; 41 | } 42 | // } Driver Code Ends 43 | -------------------------------------------------------------------------------- /Array/Ninja And The Sorted Check.cpp: -------------------------------------------------------------------------------- 1 | int isSorted(int n, vector a) { 2 | // Write your code here. 3 | for(int i = 0; i <= n - 1; i++) { 4 | if(a[i] < a[i-1]) 5 | return 0; 6 | } 7 | return 1; 8 | } 9 | -------------------------------------------------------------------------------- /Array/Perfect-Arrays.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | //Initial Template for C++ 3 | 4 | #include 5 | using namespace std; 6 | 7 | // } Driver Code Ends 8 | //User function Template for C++ 9 | 10 | class Solution{ 11 | public: 12 | bool IsPerfect(int a[],int n) 13 | { 14 | // Complete the function 15 | for(int i = 0; i >t; 29 | while(t--) 30 | { 31 | int n;cin>>n; 32 | int a[n]; 33 | 34 | for(int i=0;i>a[i]; 36 | Solution ob; 37 | if(ob.IsPerfect(a,n)) 38 | cout<<"PERFECT\n"; 39 | else 40 | cout<<"NOT PERFECT\n"; 41 | 42 | } 43 | 44 | } 45 | // } Driver Code Ends 46 | -------------------------------------------------------------------------------- /Array/Print-Elements-of-Array.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | 4 | using namespace std; 5 | 6 | 7 | // } Driver Code Ends 8 | //User function template for C++ 9 | class Solution{ 10 | public: 11 | //Just print the space seperated array elements 12 | void printArray(int arr[], int n) { 13 | // code here 14 | for(int i = 0; i < n; i++) { 15 | cout << arr[i] << " " ; 16 | } 17 | } 18 | }; 19 | 20 | //{ Driver Code Starts. 21 | 22 | int main() { 23 | int t; 24 | cin >> t; 25 | while (t--) { 26 | int n, i; 27 | cin >> n; 28 | int arr[n]; 29 | for (i = 0; i < n; i++) { 30 | cin >> arr[i]; 31 | } 32 | Solution ob; 33 | ob.printArray(arr, n); 34 | cout << "\n"; 35 | } 36 | return 0; 37 | } 38 | 39 | // } Driver Code Ends 40 | -------------------------------------------------------------------------------- /Array/Remove Duplicates from Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | int removeDuplicates(vector &arr, int n) { 2 | // Write your code here. 3 | int i = 0; 4 | for(int j = 1; j < n; j++) { 5 | if (arr[i] != arr[j]) { 6 | arr[i + 1] = arr[j]; 7 | i++; 8 | } 9 | } 10 | return (i+1); 11 | } 12 | -------------------------------------------------------------------------------- /Array/Reverse sub array.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | 4 | using namespace std; 5 | 6 | 7 | // } Driver Code Ends 8 | //User function template for C++ 9 | class Solution{ 10 | public: 11 | void reverseSubArray(int *arr, int n, int l, int r) { 12 | int left = l - 1; 13 | int right = r - 1; 14 | // code here 15 | while(left < right) { 16 | swap(arr[left], arr[right]) ; 17 | left++; 18 | right--; 19 | } 20 | } 21 | }; 22 | 23 | //{ Driver Code Starts. 24 | 25 | int main() { 26 | int t; 27 | cin >> t; 28 | while (t--) { 29 | int n, l, r; 30 | cin >> n; 31 | int arr[n]; 32 | for (int i = 0; i < n; i++) { 33 | cin >> arr[i]; 34 | } 35 | cin >> l >> r; 36 | Solution ob; 37 | ob.reverseSubArray(arr, n, l, r); 38 | for (int i = 0; i < n; i++) { 39 | cout << arr[i] << " "; 40 | } 41 | cout << "\n"; 42 | } 43 | return 0; 44 | } 45 | 46 | // } Driver Code Ends 47 | -------------------------------------------------------------------------------- /Array/Reverse-an-Array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int t; 6 | cin>>t; 7 | while(t--) { 8 | int n; 9 | cin>>n; 10 | int arr[n]; 11 | 12 | for(int i = 0; i < n; i++) { 13 | cin>>arr[i]; 14 | } 15 | for(int i = n - 1; i >= 0; i--) { 16 | cout << arr[i] << " "; 17 | } 18 | cout << endl; 19 | } 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /Array/Rotate array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | void leftRotateArray(int arr[], int n, int k) { 6 | k = k % n; 7 | int temp[k]; 8 | for(int i = 0; i < k; i++) { 9 | temp[i] = arr[i]; 10 | } 11 | for(int i = k; i < n; i++) { 12 | arr[i-k] = arr[i]; 13 | } 14 | for (int i = n - k; i < n; i++) { 15 | arr[i] = temp[i - (n - k)]; 16 | } 17 | } 18 | 19 | int main() { 20 | //Write your code here 21 | int n; 22 | cin >> n; 23 | int arr[n]; 24 | for(int i = 0; i < n; i++) { 25 | cin >> arr[i]; 26 | } 27 | int k; 28 | cin >> k; 29 | leftRotateArray(arr, n, k); 30 | for(int i = 0; i < n; i++) { 31 | cout << arr[i] << " "; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Array/Rotation.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | 4 | using namespace std; 5 | 6 | 7 | // } Driver Code Ends 8 | //User function template for C++ 9 | class Solution{ 10 | public: 11 | int findKRotation(int arr[], int n) { 12 | // code here 13 | int minIndex = 0; 14 | for(int i = 1; i < n; i++) { 15 | if(arr[i] < arr[minIndex]) 16 | minIndex = i; 17 | } 18 | return minIndex; 19 | } 20 | }; 21 | 22 | //{ Driver Code Starts. 23 | 24 | int main() { 25 | int t; 26 | cin >> t; 27 | while (t--) { 28 | int n, i; 29 | cin >> n; 30 | int a[n]; 31 | for (i = 0; i < n; i++) { 32 | cin >> a[i]; 33 | } 34 | Solution ob; 35 | auto ans = ob.findKRotation(a, n); 36 | cout << ans << "\n"; 37 | } 38 | return 0; 39 | } 40 | 41 | // } Driver Code Ends 42 | -------------------------------------------------------------------------------- /Array/Second largest element in the array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | int findSecondLargest(int n, vector &arr) 3 | { 4 | // Write your code here. 5 | // int largest = arr[0], secondLargest = -1; 6 | // for(int i = 1; i < n; i++) { 7 | // if(arr[i] > largest){ 8 | // secondLargest = largest; 9 | // largest = arr[i]; 10 | // } 11 | // else if(arr[i] < largest && arr[i] > secondLargest) { 12 | // secondLargest = arr[i]; 13 | // } 14 | // } 15 | // return secondLargest; 16 | sort(arr.begin(), arr.end()); 17 | int i = 0; 18 | while(i < n) { 19 | if(arr[n-1] != arr[n-1-i]){ 20 | return arr[n-1-i]; 21 | }else { 22 | i++; 23 | } 24 | } 25 | return -1; 26 | } 27 | -------------------------------------------------------------------------------- /Array/Sort 0 1 2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | void sort012(int *arr, int n) 3 | { 4 | // Write your code here 5 | int low = 0, mid = 0, high = n - 1; 6 | 7 | while(mid <= high) { 8 | switch(arr[mid]) { 9 | case 0: 10 | swap(arr[low++], arr[mid++]); 11 | break; 12 | 13 | case 1: 14 | arr[mid++]; 15 | break; 16 | 17 | case 2: 18 | swap(arr[mid], arr[high--]); 19 | break; 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Array/Sum-of-Array.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | 4 | using namespace std; 5 | 6 | // } Driver Code Ends 7 | //User function template for C++ 8 | class Solution{ 9 | public: 10 | // function to return sum of elements 11 | // in an array of size n 12 | int sum(int arr[], int n) { 13 | // code here 14 | int sum = 0; 15 | for(int i = 0; i < n; i++) { 16 | sum += arr[i]; 17 | } 18 | return sum; 19 | } 20 | }; 21 | 22 | //{ Driver Code Starts. 23 | 24 | int main() { 25 | int t; 26 | cin >> t; 27 | while (t--) { 28 | int n, i; 29 | cin >> n; 30 | int arr[n]; 31 | for (i = 0; i < n; i++) { 32 | cin >> arr[i]; 33 | } 34 | Solution ob; 35 | auto ans = ob.sum(arr, n); 36 | cout << ans << "\n"; 37 | } 38 | return 0; 39 | } 40 | // } Driver Code Ends 41 | -------------------------------------------------------------------------------- /Bit Magic/136-Single-Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int singleNumber(vector& nums) { 4 | int count = 0; 5 | for(int i = 0; i < nums.size(); i++) { 6 | count^=nums[i]; 7 | } 8 | return count; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /Bit Magic/1611. Minimum One Bit Operations to Make Integers Zero.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minimumOneBitOperations(int n) { 4 | if (n <= 1) return n; 5 | int count = 0; 6 | while ((1< 0) { 6 | count++; 7 | n = n & (n - 1); 8 | } 9 | return count; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /Bit Magic/201. Bitwise AND of Numbers Range.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public: 4 | int rangeBitwiseAnd(int left, int right) { 5 | int cnt = 0; 6 | while (left != right) { 7 | left >>= 1; 8 | right >>= 1; 9 | cnt++; 10 | } 11 | return (left << cnt); 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Bit Magic/231-Power-of-Two.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPowerOfTwo(int n) { 4 | if(n == 0) 5 | return false; 6 | while(n != 1) { 7 | if(n % 2 != 0) 8 | return false; 9 | n = n/2; 10 | } 11 | return true; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Bit Magic/Check-whether-K-th-bit-is-set-or-not .cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | //Initial Template for C++ 3 | 4 | #include 5 | using namespace std; 6 | 7 | 8 | // } Driver Code Ends 9 | //User function Template for C++ 10 | 11 | 12 | class Solution 13 | { 14 | public: 15 | // Function to check if Kth bit is set or not. 16 | bool checkKthBit(int n, int k) 17 | { 18 | // Your code here 19 | // It can be a one liner logic!! Think of it!! 20 | return (n & (1 << (k))); 21 | } 22 | }; 23 | 24 | // { Driver Code Starts. 25 | 26 | // Driver Code 27 | int main() 28 | { 29 | int t; 30 | cin>>t;//taking testcases 31 | while(t--) 32 | { 33 | long long n; 34 | cin>>n;//input n 35 | int k; 36 | cin>>k;//bit number k 37 | Solution obj; 38 | if(obj.checkKthBit(n, k)) 39 | cout << "Yes" << endl; 40 | else 41 | cout << "No" << endl; 42 | } 43 | return 0; 44 | } // } Driver Code Ends 45 | -------------------------------------------------------------------------------- /Bit Magic/Find-the-element-that-appears-once.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | 4 | using namespace std; 5 | 6 | // } Driver Code Ends 7 | //User function template for C++ 8 | class Solution{ 9 | public: 10 | int search(int A[], int N){ 11 | //code 12 | int count = 0; 13 | for(int i = 0; i < N; i++) { 14 | count = count^A[i]; 15 | } 16 | return count; 17 | } 18 | }; 19 | 20 | // { Driver Code Starts. 21 | 22 | // Driver program 23 | int main() 24 | { 25 | int t,len; 26 | cin>>t; 27 | while(t--) 28 | { 29 | cin>>len; 30 | int arr[len]; 31 | for(int i=0;i>arr[i]; 33 | } 34 | Solution ob; 35 | cout< 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | class Solution { 7 | public: 8 | int setBits(int N) { 9 | // Write Your Code here 10 | int cnt = __builtin_popcount(N); 11 | return cnt; 12 | } 13 | }; 14 | 15 | // { Driver Code Starts. 16 | int main() { 17 | int t; 18 | cin >> t; 19 | while (t--) { 20 | int N; 21 | cin >> N; 22 | 23 | Solution ob; 24 | int cnt = ob.setBits(N); 25 | cout << cnt << endl; 26 | } 27 | return 0; 28 | } 29 | // } Driver Code Ends 30 | -------------------------------------------------------------------------------- /Bit Magic/Power-Set.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | class Solution{ 7 | public: 8 | vector AllPossibleStrings(string s){ 9 | // Code here 10 | int n = s.length(); 11 | vectorv; 12 | for(int i = 1; i < (1 << n); i++) { 13 | string temp; 14 | for(int j = 0; j < n; j++) 15 | if(i & (1 << j)) 16 | temp+=s[j]; 17 | v.push_back(temp); 18 | } 19 | sort(v.begin(), v.end()); 20 | return v; 21 | } 22 | }; 23 | 24 | // { Driver Code Starts. 25 | int main(){ 26 | int tc; 27 | cin >> tc; 28 | while(tc--){ 29 | string s; 30 | cin >> s; 31 | Solution ob; 32 | vector res = ob.AllPossibleStrings(s); 33 | for(auto i : res) 34 | cout << i <<" "; 35 | cout << "\n"; 36 | 37 | } 38 | return 0; 39 | } // } Driver Code Ends 40 | -------------------------------------------------------------------------------- /Bit Magic/Power-of-2.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | //Initial Template for C++ 3 | 4 | #include 5 | using namespace std; 6 | 7 | 8 | // } Driver Code Ends 9 | //User function Template for C++ 10 | 11 | class Solution{ 12 | public: 13 | // Function to check if given number n is a power of two. 14 | bool isPowerofTwo(long long n){ 15 | 16 | // Your code here 17 | return (n != 0) && ((n & (n - 1)) == 0); 18 | } 19 | }; 20 | 21 | // { Driver Code Starts. 22 | 23 | // Driver code 24 | int main() 25 | { 26 | 27 | int t; 28 | cin>>t;//testcases 29 | 30 | for(int i=0;i>n; 34 | 35 | Solution ob; 36 | if(ob.isPowerofTwo(n))//Now, if log2 produces an integer not decimal then we are sure raising 2 to this value 37 | cout<<"YES"<& arr, int k) { 4 | int N = arr.size(); 5 | int K = k + 1; 6 | 7 | int dp[k + 1]; 8 | memset(dp, 0, sizeof(dp)); 9 | 10 | for (int start = N - 1; start >= 0; start--) { 11 | int currMax = 0; 12 | int end = min(N, start + k); 13 | 14 | for (int i = start; i < end; i++) { 15 | currMax = max(currMax, arr[i]); 16 | dp[start % K] = max(dp[start % K], dp[(i + 1) % K] + currMax * (i - start + 1)); 17 | } 18 | } 19 | return dp[0]; 20 | } 21 | }; 22 | 23 | 24 | -------------------------------------------------------------------------------- /DP/1143. Longest Common Subsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestCommonSubsequence(string text1, string text2) { 4 | const int m = text1.length(); 5 | const int n = text2.length(); 6 | // dp[i][j] := LCS's length of text1[0..i) and text2[0..j) 7 | vector> dp(m + 1, vector(n + 1)); 8 | 9 | for (int i = 0; i < m; ++i) 10 | for (int j = 0; j < n; ++j) 11 | dp[i + 1][j + 1] = text1[i] == text2[j] 12 | ? 1 + dp[i][j] 13 | : max(dp[i][j + 1], dp[i + 1][j]); 14 | 15 | return dp[m][n]; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /DP/119. Pascal's Triangle II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector getRow(int rowIndex) { 4 | std::vector currentRow, previousRow; 5 | 6 | for (int i = 0; i <= rowIndex; i++) { 7 | currentRow.clear(); 8 | for (int j = 0; j <= i; j++) { 9 | if (j == 0 || j == i) { 10 | currentRow.push_back(1); // The first and last elements are always 1. 11 | } else { 12 | int sum = previousRow[j - 1] + previousRow[j]; 13 | currentRow.push_back(sum); 14 | } 15 | } 16 | 17 | previousRow = currentRow; 18 | } 19 | 20 | return currentRow; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /DP/1578. Minimum Time to Make Rope Colorful.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minCost(string colors, vector& neededTime) { 4 | char previousColor = 'A'; 5 | int previousTime = 0; 6 | int currentCost, previousCost; 7 | currentCost = previousCost = 0; 8 | for(int i = 1; i <= colors.size(); i++) { 9 | if(colors[i - 1] == previousColor) { 10 | currentCost = previousCost + min(neededTime[i - 1], previousTime); 11 | previousTime = max(neededTime[i - 1], previousTime); 12 | }else { 13 | currentCost = previousCost; 14 | previousColor = colors[i - 1]; 15 | previousTime = neededTime[i - 1]; 16 | } 17 | previousCost = currentCost; 18 | } 19 | return previousCost; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /DP/279. Perfect Squares.cpp: -------------------------------------------------------------------------------- 1 | // class Solution { 2 | // public: 3 | // int solve(int n) { 4 | // if(n == 0) return 0; 5 | 6 | // int result = n; 7 | // for(int i = 1; i <= sqrt(n); i++) { 8 | // result = min(result, 1 + solve(n - i * i)); 9 | // } 10 | 11 | // return result; 12 | // } 13 | // int numSquares(int n) { 14 | // return solve(n); 15 | // } 16 | // }; 17 | 18 | class Solution { 19 | public: 20 | int numSquares(int n) { 21 | vector dp(n + 1, INT_MAX); 22 | 23 | dp[0] = 0; 24 | 25 | for(int i = 1; i <= n; i++) { 26 | for(int j = 1; j * j <= i; j++) { 27 | dp[i] = min(dp[i], dp[i - j * j] + 1); 28 | } 29 | } 30 | return dp[n]; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /DP/300. Longest Increasing Subsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lengthOfLIS(std::vector& nums) { 4 | if (nums.empty()) { 5 | return 0; 6 | } 7 | 8 | int n = nums.size(); 9 | std::vector dp(n, 1); 10 | 11 | for (int i = 1; i < n; ++i) { 12 | for (int j = 0; j < i; ++j) { 13 | if (nums[i] > nums[j]) { 14 | dp[i] = std::max(dp[i], dp[j] + 1); 15 | } 16 | } 17 | } 18 | 19 | return *std::max_element(dp.begin(), dp.end()); 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /DP/509. Fibonacci Number.cpp: -------------------------------------------------------------------------------- 1 | // recursive solution 2 | // class Solution { 3 | // public: 4 | // int fib(int n) { 5 | // if(n <= 1) return n; 6 | // return fib(n - 1) + fib(n - 2); 7 | // } 8 | // }; 9 | 10 | // Memoization (DP) 11 | // class Solution { 12 | // public: 13 | // int f(int n, vector&dp) { 14 | // if(n <= 1) return n; 15 | // if(dp[n] != -1) return dp[n]; 16 | // return dp[n] = f(n - 1, dp) + f(n - 2, dp); 17 | // } 18 | // int fib(int n) { 19 | // vectordp(n + 1, -1); 20 | // return f(n, dp); 21 | // } 22 | // }; 23 | 24 | // Tabluation (DP) 25 | class Solution { 26 | public: 27 | int fib(int n) { 28 | if(n <= 1) return n; 29 | int prev = 1; 30 | int prev2 = 0; 31 | for(int i = 2; i <= n; i++) { 32 | int current = prev + prev2; 33 | prev2 = prev; 34 | prev = current; 35 | } 36 | return prev; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /DP/629. K Inverse Pairs Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int kInversePairs(int n, int k) { 4 | int dp[1001][1001] = {1}; 5 | for (int i = 1; i <= n; i++) { 6 | for (int j = 0; j <= k; j++) { 7 | for (int x = 0; x <= min(j, i - 1); x++) { 8 | 9 | if (j - x >= 0) { 10 | dp[i][j] = (dp[i][j] + dp[i - 1][j - x]) % 1000000007; 11 | } 12 | } 13 | } 14 | } 15 | 16 | return dp[n][k]; 17 | } 18 | }; 19 | 20 | 21 | -------------------------------------------------------------------------------- /DP/70. Climbing Stairs.cpp: -------------------------------------------------------------------------------- 1 | // class Solution { 2 | // public: 3 | 4 | // int climb(int current, int n) { 5 | // if(current > n) { 6 | // return 0; 7 | // } 8 | 9 | // if(current == n) { 10 | // return 1; 11 | // } 12 | 13 | // return climb(current + 1, n) + climb(current + 2, n); 14 | // } 15 | // int climbStairs(int n) { 16 | // return climb(0, n); 17 | // } 18 | // }; 19 | 20 | class Solution { 21 | public: 22 | int climbStairs(int n) { 23 | if(n <= 2) return n; 24 | 25 | int dp[n + 1]; 26 | dp[1] = 1; 27 | dp[2] = 2; 28 | 29 | for(int i = 3; i <= n; i++) { 30 | dp[i] = dp[i - 1] + dp[i - 2]; 31 | } 32 | return dp[n]; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /DP/746. Min Cost Climbing Stairs.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minCostClimbingStairs(vector& cost) { 4 | int n = cost.size(); 5 | vector dp(n + 1, 0); 6 | 7 | for (int i = 2; i <= n; i++) { 8 | dp[i] = min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]); 9 | } 10 | 11 | return dp[n]; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /DP/91. Decode Ways.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numDecodings(string s) { 4 | if(s.empty() || s[0] == '0') { 5 | return 0; 6 | } 7 | 8 | int n = s.length(); 9 | vectordp(n + 1, 0); 10 | dp[0] = 1; 11 | dp[1] = 1; 12 | 13 | for(int i = 2; i <= n; ++i) { 14 | int oneDigit = s[i - 1] - '0'; 15 | int twoDigit = stoi(s.substr(i - 2, 2)); 16 | 17 | if(oneDigit != 0) { 18 | dp[i] += dp[i - 1]; 19 | } 20 | 21 | if(10 <= twoDigit && twoDigit <= 26) { 22 | dp[i] += dp[i - 2]; 23 | } 24 | } 25 | return dp[n]; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Graph/547. Number of Provinces.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void dfs(int j, vector &vis, vector adj[]) { 4 | vis[j] = true; 5 | for(auto x : adj[j]) { 6 | if(!vis[x]) { 7 | dfs(x, vis, adj); 8 | } 9 | } 10 | } 11 | int findCircleNum(vector>& isConnected) { 12 | int n = (int)isConnected.size(); 13 | const int N = 444; 14 | vectoradj[N]; 15 | vectorvis(N); 16 | for(int i = 0; i < n; i++) { 17 | for(int j = 0; j < n; j++) { 18 | if(isConnected[i][j] == 1 && i != j) { 19 | adj[i].push_back(j); 20 | } 21 | } 22 | } 23 | vis.assign(n+4, false); 24 | int count = 0; 25 | for(int i = 0; i < n; i++) { 26 | if(!vis[i]) { 27 | dfs(i, vis, adj); 28 | count++; 29 | } 30 | } 31 | return count; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /Greedy/1877. Minimize Maximum Pair Sum in Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minPairSum(vector& nums) { 4 | sort(nums.begin(), nums.end()); 5 | int low = 0; 6 | int high = nums.size() - 1; 7 | int minMaxPairSum = 0; 8 | while(low <= high) { 9 | int currentPairSum = nums[low] + nums[high]; 10 | minMaxPairSum = max(minMaxPairSum, currentPairSum); 11 | low++; 12 | high--; 13 | } 14 | return minMaxPairSum; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Greedy/2971. Find Polygon With the Largest Perimeter.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long largestPerimeter(vector& nums) { 4 | long long sum = 0; 5 | sort(nums.begin(),nums.end()); 6 | for(auto i : nums) sum += i; 7 | int n = nums.size(); 8 | for(int i = n - 1; i >= 2; i--){ 9 | sum -= nums[i]; 10 | if(sum > nums[i]){ 11 | return sum + nums[i]; 12 | } 13 | } 14 | return -1; 15 | } 16 | }; 17 | 18 | -------------------------------------------------------------------------------- /Greedy/452. Minimum Number of Arrows to Burst Balloons.cpp: -------------------------------------------------------------------------------- 1 | bool comp (vector &x, vector &y) { 2 | return x[1] < y[1]; 3 | } 4 | class Solution { 5 | public: 6 | int findMinArrowShots(vector>& points) { 7 | if(points.size() == 0) return 0; 8 | if(points.size() == 1) return 1; 9 | 10 | int arrows = 1; 11 | 12 | sort(points.begin(), points.end(), comp); 13 | 14 | int prev = points[0][1]; 15 | 16 | for(int i = 1; i < points.size(); i++) { 17 | if(points[i][0] <= prev) continue; 18 | arrows++; 19 | prev = points[i][1]; 20 | } 21 | return arrows; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Greedy/455. Assign Cookies.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findContentChildren(vector& g, vector& s) { 4 | int count = 0; 5 | sort(s.begin(), s.end()); 6 | sort(g.begin(), g.end()); 7 | int i = 0; 8 | int j = 0; 9 | while (i < g.size() && j < s.size()){ 10 | if(g[i] <= s[j]) { 11 | count++; 12 | i++; 13 | } 14 | j++; 15 | } 16 | return count; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Greedy/575. Distribute Candies.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int distributeCandies(vector& candyType) { 4 | sets; 5 | for(int i : candyType) { 6 | s.insert(i); 7 | } 8 | return min(candyType.size() / 2, s.size()); 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /Greedy/678. Valid Parenthesis String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool checkValidString(string s) { 4 | int leftMin = 0, leftMax = 0; 5 | 6 | for(char c : s) { 7 | if(c == '(') { 8 | leftMin++; 9 | leftMax++; 10 | }else if(c == ')') { 11 | leftMin--; 12 | leftMax--; 13 | }else { 14 | leftMin--; 15 | leftMax++; 16 | } 17 | 18 | if(leftMax < 0) return false; 19 | if(leftMin < 0) leftMin = 0; 20 | } 21 | 22 | return leftMin == 0; 23 | 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Greedy/Chocolate Distribution Problem.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | class Solution{ 7 | public: 8 | long long findMinDiff(vector a, long long n, long long m){ 9 | //code 10 | sort(a.begin(), a.end()); 11 | 12 | int i = 0; 13 | int j = m - 1; 14 | 15 | int mini = INT_MAX; 16 | 17 | while(j < a.size()) { 18 | int difference = a[j] - a[i]; 19 | mini = min(mini, difference); 20 | i++; 21 | j++; 22 | } 23 | return mini; 24 | } 25 | }; 26 | 27 | //{ Driver Code Starts. 28 | int main() { 29 | long long t; 30 | cin>>t; 31 | while(t--) 32 | { 33 | long long n; 34 | cin>>n; 35 | vector a; 36 | long long x; 37 | for(long long i=0;i>x; 40 | a.push_back(x); 41 | } 42 | 43 | long long m; 44 | cin>>m; 45 | Solution ob; 46 | cout<>& paths) { 4 | unordered_set cities; 5 | 6 | // Collect outgoing cities 7 | for (const auto& path : paths) { 8 | cities.insert(path[0]); 9 | } 10 | 11 | // Find destination city with no outgoing path 12 | for (const auto& path : paths) { 13 | const std::string& dest = path[1]; 14 | if (cities.find(dest) == cities.end()) { 15 | return dest; 16 | } 17 | } 18 | 19 | return ""; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Hashing/49. Group Anagrams.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> groupAnagrams(vector& strs) { 4 | unordered_map> umap; 5 | for(auto x : strs) { 6 | string word = x; 7 | sort(word.begin(), word.end()); 8 | umap[word].push_back(x); 9 | } 10 | 11 | vector> result; 12 | for(auto x : umap) { 13 | result.push_back(x.second); 14 | } 15 | return result; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Hashing/Frequency In A Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | int countOccurrences(vector < int > arr, int x) { 2 | // Write your code here. 3 | int n = arr.size(); 4 | int count = 0; 5 | for(int i = 0; i < n; i++) { 6 | if(arr[i] == x) 7 | count++; 8 | } 9 | return count; 10 | } 11 | -------------------------------------------------------------------------------- /Hashmap/1481. Least Number of Unique Integers after K Removals.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findLeastNumOfUniqueInts(vector& arr, int k) { 4 | unordered_map mp; 5 | for (int& x : arr) { 6 | mp[x]++; 7 | } 8 | 9 | vector freq; 10 | for (auto& pair : mp) { 11 | freq.push_back(pair.second); 12 | } 13 | 14 | sort(begin(freq), end(freq)); 15 | 16 | int count = 0; 17 | for (int& f : freq) { 18 | if (k >= f) { 19 | k -= f; 20 | count++; 21 | } else { 22 | break; 23 | } 24 | } 25 | 26 | return freq.size() - count; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Hashmap/1496. Path Crossing.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPathCrossing(string path) { 4 | unordered_set visitedPoints; 5 | int currentX = 0, currentY = 0; 6 | visitedPoints.insert(to_string(currentX) + "," + to_string(currentY)); 7 | 8 | for (auto direction : path) { 9 | if (direction == 'N') ++currentY; 10 | else if (direction == 'S') --currentY; 11 | else if (direction == 'E') ++currentX; 12 | else --currentX; 13 | 14 | if (visitedPoints.count(to_string(currentX) + "," + to_string(currentY))) { 15 | return true; 16 | } 17 | 18 | visitedPoints.insert(to_string(currentX) + "," + to_string(currentY)); 19 | } 20 | 21 | return false; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Hashmap/26. Remove Duplicates from Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int removeDuplicates(vector& nums) { 4 | // int j = 1; 5 | // for(int i = 0; i < nums.size() - 1; i++) { 6 | // if(nums[i] != nums[i + 1]) { 7 | // nums[j] = nums[i + 1]; 8 | // j++; 9 | // } 10 | // } 11 | // return j; 12 | 13 | map mp; 14 | for(int i = 0; i < nums.size(); i++) { 15 | mp[nums[i]]++; 16 | } 17 | 18 | int i = 0; 19 | for(map::iterator it = mp.begin(); it!=mp.end(); it++) { 20 | int a = it->first; 21 | nums[i] = a; 22 | i++; 23 | } 24 | return i; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Hashmap/2870. Minimum Number of Operations to Make Array Empty.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minOperations(vector& nums) { 4 | std::unordered_map numCount; 5 | 6 | for (int num : nums) { 7 | numCount[num]++; 8 | } 9 | 10 | int operations = 0; 11 | 12 | for (const auto& [num, count] : numCount) { 13 | int remainingCount = count; 14 | while (remainingCount > 0) { 15 | if (remainingCount == 1) { 16 | return -1; 17 | } 18 | if (remainingCount == 4 || remainingCount == 2) { 19 | remainingCount -= 2; 20 | operations++; 21 | } else { 22 | remainingCount -= 3; 23 | operations++; 24 | } 25 | } 26 | } 27 | 28 | return operations; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Heap/Check Max-Heap.cpp: -------------------------------------------------------------------------------- 1 | bool isMaxHeap(int arr[], int n) { 2 | // Write your code here 3 | // Start from the first non-leaf node and move up the tree 4 | for (int i = 0; i <= (n / 2) - 1; i++) { 5 | // Calculate the indices of the left and right children 6 | int leftChild = 2 * i + 1; 7 | int rightChild = 2 * i + 2; 8 | 9 | // Check if the left child exists and is greater than the current node 10 | if (leftChild < n && arr[leftChild] > arr[i]) { 11 | return false; 12 | } 13 | 14 | // Check if the right child exists and is greater than the current node 15 | if (rightChild < n && arr[rightChild] > arr[i]) { 16 | return false; 17 | } 18 | } 19 | 20 | // If the loop completes without returning false, it's a max-heap 21 | return true; 22 | } 23 | -------------------------------------------------------------------------------- /Heap/Kth largest element.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | int kthLargest(vector&arr, int k) { 4 | // Write your code here 5 | std::priority_queue, std::greater> minHeap; 6 | 7 | // Insert the first k elements into the min-heap 8 | for (int i = 0; i < k; i++) { 9 | minHeap.push(arr[i]); 10 | } 11 | 12 | // For the remaining elements, compare them with the smallest element in the heap 13 | // If the element is larger, replace the smallest element with the current element 14 | for (int i = k; i < arr.size(); i++) { 15 | if (arr[i] > minHeap.top()) { 16 | minHeap.pop(); 17 | minHeap.push(arr[i]); 18 | } 19 | } 20 | 21 | // The kth largest element will be at the top of the min-heap 22 | return minHeap.top(); 23 | } 24 | -------------------------------------------------------------------------------- /Linked List/1019. Next Greater Node In Linked List.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | vector nextLargerNodes(ListNode* head) { 14 | vectorans; 15 | while(head != NULL) { 16 | ListNode* current = head->next; 17 | int nextGreater = 0; 18 | 19 | while(current != NULL) { 20 | if(current->val > head->val) { 21 | nextGreater = current->val; 22 | break; 23 | } 24 | current = current->next; 25 | } 26 | ans.push_back(nextGreater); 27 | head = head->next; 28 | } 29 | return ans; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Linked List/141. Linked List Cycle.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | bool hasCycle(ListNode *head) { 12 | if(head == NULL || head->next == NULL) { 13 | return false; 14 | } 15 | ListNode* slow = head; 16 | ListNode* fast = head; 17 | 18 | while(fast->next != NULL && fast->next->next != NULL) { 19 | fast = fast->next->next; 20 | slow = slow->next; 21 | if(fast == slow) { 22 | return true; 23 | } 24 | } 25 | return false; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Linked List/142. Linked List Cycle II.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode *detectCycle(ListNode *head) { 12 | if(head == NULL || head->next == NULL) { 13 | return NULL; 14 | } 15 | ListNode* slow = head; 16 | ListNode* fast = head; 17 | ListNode* entry = head; 18 | 19 | while(fast->next != NULL && fast->next->next != NULL) { 20 | slow = slow->next; 21 | fast = fast->next->next; 22 | if(slow == fast) { 23 | while(slow != entry) { 24 | entry = entry->next; 25 | slow = slow->next; 26 | } 27 | return entry; 28 | } 29 | } 30 | return NULL; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /Linked List/1721. Swapping Nodes in a Linked List.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* swapNodes(ListNode* head, int k) { 14 | ListNode* slow = head; 15 | ListNode* fast = head; 16 | while(--k) { 17 | fast = fast->next; 18 | } 19 | ListNode* first = fast; 20 | while(fast->next != NULL) { 21 | fast = fast->next; 22 | slow = slow->next; 23 | } 24 | swap(first->val, slow->val); 25 | return head; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Linked List/19. Remove Nth Node From End of List.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | 14 | ListNode* removeNthFromEnd(ListNode* head, int n) { 15 | ListNode* dummyNode = new ListNode(-1); 16 | 17 | dummyNode->next = head; 18 | 19 | ListNode* slow = dummyNode; 20 | ListNode* fast = dummyNode; 21 | 22 | for(int i = 0; i <=n; i++) { 23 | fast = fast->next; 24 | } 25 | 26 | while(fast != NULL) { 27 | fast = fast->next; 28 | slow = slow->next; 29 | } 30 | 31 | slow->next = slow->next->next; 32 | 33 | return dummyNode->next; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /Linked List/2095. Delete the Middle Node of a Linked List.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* deleteMiddle(ListNode* head) { 14 | if(head == NULL || head->next == NULL) { 15 | return NULL; 16 | } 17 | 18 | if(head->next->next == NULL) { 19 | head->next = NULL; 20 | return head; 21 | } 22 | 23 | ListNode* slow = head; 24 | ListNode* fast = head; 25 | 26 | while(fast != NULL && fast->next != NULL) { 27 | fast = fast->next->next; 28 | slow = slow->next; 29 | } 30 | 31 | slow->val = slow->next->val; 32 | slow->next = slow->next->next; 33 | 34 | return head; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /Linked List/234. Palindrome Linked List.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | bool isPalindrome(ListNode* head) { 14 | ListNode* slow = head; 15 | stacks; 16 | while(slow != NULL) { 17 | s.push(slow->val); 18 | slow = slow->next; 19 | } 20 | while(head != NULL) { 21 | int i = s.top(); 22 | s.pop(); 23 | if(head->val != i) { 24 | return false; 25 | } 26 | head = head->next; 27 | } 28 | return true; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Linked List/237. Delete Node in a Linked List.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | void deleteNode(ListNode* node) { 12 | ListNode* curr = node->next; 13 | node->val = curr->val; 14 | node->next = curr->next; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Linked List/82. Remove Duplicates from Sorted List II.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* deleteDuplicates(ListNode* head) { 14 | ListNode* dummy = new ListNode(0, head); 15 | 16 | ListNode* prev = dummy; 17 | 18 | while(head != NULL) { 19 | if(head->next != NULL && head->val == head->next->val) { 20 | while(head->next != NULL && head->val == head->next->val) { 21 | head=head->next; 22 | } 23 | prev->next = head->next; 24 | }else { 25 | prev = prev->next; 26 | } 27 | head = head->next; 28 | } 29 | return dummy->next; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Linked List/83. Remove Duplicates from Sorted List.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* deleteDuplicates(ListNode* head) { 14 | ListNode* current = head; 15 | while((current != NULL) && (current->next != NULL)) { 16 | if(current->val == current->next->val) 17 | current->next = current->next->next; 18 | else 19 | current = current->next; 20 | } 21 | return head; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Linked List/876. Middle of the Linked List.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* middleNode(ListNode* head) { 14 | if(head == NULL || head->next == NULL) { 15 | return head; 16 | } 17 | ListNode* slow = head; 18 | ListNode* fast = head; 19 | 20 | while((fast != NULL) && (fast->next != NULL)) { 21 | fast = fast->next->next; 22 | slow = slow->next; 23 | } 24 | return slow; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Linked List/Code : Reverse LL (Recursive).cpp: -------------------------------------------------------------------------------- 1 | #include 2 | /**************************************************************** 3 | 4 | Following is the class structure of the Node class: 5 | 6 | class Node 7 | { 8 | public: 9 | int data; 10 | Node *next; 11 | Node(int data) 12 | { 13 | this->data = data; 14 | this->next = NULL; 15 | } 16 | }; 17 | 18 | *****************************************************************/ 19 | 20 | Node *reverseLinkedListRec(Node *head) 21 | { 22 | //Write your code here 23 | if(head == NULL || head->next == NULL) { 24 | return head; 25 | } 26 | 27 | Node* smallAns = reverseLinkedListRec(head->next); 28 | Node* temp = smallAns; 29 | 30 | while(temp->next != NULL) { 31 | temp = temp->next; 32 | } 33 | 34 | temp->next = head; 35 | head->next = NULL; 36 | return smallAns; 37 | } 38 | -------------------------------------------------------------------------------- /Linked List/Code: Midpoint of LL.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************** 2 | 3 | Following is the class structure of the Node class: 4 | 5 | class Node 6 | { 7 | public: 8 | int data; 9 | Node *next; 10 | Node(int data) 11 | { 12 | this->data = data; 13 | this->next = NULL; 14 | } 15 | }; 16 | 17 | *****************************************************************/ 18 | 19 | Node *midPoint(Node *head) 20 | { 21 | // Write your code here 22 | if(head == NULL || head->next == NULL) { 23 | return head; 24 | } 25 | Node* slow = head; 26 | Node* fast = head->next; 27 | 28 | while(fast != NULL && fast->next != NULL) { 29 | fast = fast->next->next; 30 | slow = slow->next; 31 | } 32 | return slow; 33 | 34 | } 35 | -------------------------------------------------------------------------------- /Linked List/Code: Reverse LL (Iterative).cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************** 2 | 3 | Following is the class structure of the Node class: 4 | 5 | class Node 6 | { 7 | public: 8 | int data; 9 | Node *next; 10 | Node(int data) 11 | { 12 | this->data = data; 13 | this->next = NULL; 14 | } 15 | }; 16 | 17 | *****************************************************************/ 18 | 19 | Node *reverseLinkedList(Node *head) { 20 | // Write your code here 21 | Node* prev = NULL; 22 | Node* current = head; 23 | 24 | while(current != NULL) { 25 | Node* next = current->next; 26 | current->next = prev; 27 | prev = current; 28 | current = next; 29 | } 30 | return prev; 31 | } 32 | -------------------------------------------------------------------------------- /Linked List/Delete node.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************** 2 | 3 | Following is the class structure of the Node class: 4 | 5 | class Node 6 | { 7 | public: 8 | int data; 9 | Node *next; 10 | Node(int data) 11 | { 12 | this->data = data; 13 | this->next = NULL; 14 | } 15 | }; 16 | 17 | *****************************************************************/ 18 | 19 | Node *deleteNode(Node *head, int pos) 20 | { 21 | // Write your code here. 22 | if(head == NULL) { 23 | return head; 24 | } 25 | if(pos == 0) { 26 | return head->next; 27 | } 28 | Node* curr = head; 29 | int currPos = 0; 30 | 31 | while(curr != NULL && currPos < pos - 1) { 32 | ++currPos; 33 | curr = curr->next; 34 | } 35 | 36 | if(curr == NULL || curr -> next == NULL) { 37 | return head; 38 | } 39 | 40 | curr->next = curr->next->next; 41 | 42 | return head; 43 | } 44 | -------------------------------------------------------------------------------- /Linked List/Eliminate Duplicates.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************** 2 | 3 | Following is the class structure of the Node class: 4 | 5 | class Node 6 | { 7 | public: 8 | int data; 9 | Node *next; 10 | Node(int data) 11 | { 12 | this->data = data; 13 | this->next = NULL; 14 | } 15 | }; 16 | 17 | *****************************************************************/ 18 | 19 | Node *removeDuplicates(Node *head) 20 | { 21 | //Write your code here 22 | Node* current = head; 23 | while(current != NULL && current->next != NULL) { 24 | if(current->data == current->next->data) { 25 | current->next = current->next->next; 26 | }else 27 | current = current->next; 28 | } 29 | return head; 30 | } 31 | -------------------------------------------------------------------------------- /Linked List/Find a Node in LL (recursive).cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************** 2 | 3 | Following is the class structure of the Node class: 4 | 5 | class Node 6 | { 7 | public: 8 | int data; 9 | Node *next; 10 | Node(int data) 11 | { 12 | this->data = data; 13 | this->next = NULL; 14 | } 15 | }; 16 | 17 | *****************************************************************/ 18 | 19 | int findNodeRec(Node *head, int n) 20 | { 21 | //Write your code here 22 | if(head == NULL) { 23 | return -1; 24 | } 25 | else if(head->data == n) { 26 | return 0; 27 | } 28 | int smallAns = findNodeRec(head->next, n); 29 | 30 | if(smallAns == -1) { 31 | return -1; 32 | } 33 | return smallAns + 1; 34 | } 35 | -------------------------------------------------------------------------------- /Linked List/Find a Node in Linked List.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************** 2 | 3 | Following is the class structure of the Node class: 4 | 5 | class Node 6 | { 7 | public: 8 | int data; 9 | Node *next; 10 | Node(int data) 11 | { 12 | this->data = data; 13 | this->next = NULL; 14 | } 15 | }; 16 | 17 | *****************************************************************/ 18 | 19 | int findNode(Node *head, int n){ 20 | // Write your code here 21 | int pos = 0; 22 | while(head != NULL) { 23 | if(head->data == n) { 24 | return pos; 25 | } 26 | pos++; 27 | head = head->next; 28 | } 29 | return -1; 30 | } 31 | -------------------------------------------------------------------------------- /Linked List/Insert node (recursive).cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************** 2 | 3 | Following is the class structure of the Node class: 4 | 5 | class Node 6 | { 7 | public: 8 | int data; 9 | Node *next; 10 | Node(int data) 11 | { 12 | this->data = data; 13 | this->next = NULL; 14 | } 15 | }; 16 | 17 | *****************************************************************/ 18 | Node* InsertNode(Node *head, int pos, Node* newNode) 19 | { 20 | if(head == NULL) { 21 | return newNode; 22 | } 23 | if(pos == 0) { 24 | newNode->next = head; 25 | return newNode; 26 | } 27 | Node *smallHead = InsertNode(head->next, pos - 1, newNode); 28 | head->next = smallHead; 29 | return head; 30 | } 31 | -------------------------------------------------------------------------------- /Linked List/Length of Linked List.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************** 2 | 3 | Following is the class structure of the Node class: 4 | 5 | class Node 6 | { 7 | public: 8 | int data; 9 | Node *next; 10 | Node() 11 | { 12 | this->data = 0; 13 | next = NULL; 14 | } 15 | Node(int data) 16 | { 17 | this->data = data; 18 | this->next = NULL; 19 | } 20 | Node(int data, Node* next) 21 | { 22 | this->data = data; 23 | this->next = next; 24 | } 25 | }; 26 | 27 | 28 | *****************************************************************/ 29 | 30 | int length(Node *head) 31 | { 32 | //Write your code here 33 | int count = 0; 34 | Node* current = head; 35 | while(current != NULL) { 36 | count++; 37 | current = current -> next; 38 | } 39 | return count; 40 | } 41 | -------------------------------------------------------------------------------- /Linked List/Palindrome Linked List.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | /**************************************************************** 3 | 4 | Following is the class structure of the Node class: 5 | 6 | class Node 7 | { 8 | public: 9 | int data; 10 | Node *next; 11 | Node(int data) 12 | { 13 | this->data = data; 14 | this->next = NULL; 15 | } 16 | }; 17 | 18 | *****************************************************************/ 19 | 20 | bool isPalindrome(Node *head) 21 | { 22 | //Write your code here 23 | Node* slow = head; 24 | stacks; 25 | while(slow != NULL) { 26 | s.push(slow->data); 27 | slow = slow->next; 28 | } 29 | while(head != NULL) { 30 | int i = s.top(); 31 | s.pop(); 32 | if(head->data != i) { 33 | return false; 34 | } 35 | head = head->next; 36 | } 37 | return true; 38 | } 39 | -------------------------------------------------------------------------------- /Linked List/Print Reversed Linked List.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************** 2 | 3 | Following is the class structure of the Node class: 4 | 5 | class Node 6 | { 7 | public: 8 | int data; 9 | Node *next; 10 | Node(int data) 11 | { 12 | this->data = data; 13 | this->next = NULL; 14 | } 15 | }; 16 | 17 | *****************************************************************/ 18 | 19 | void printReverse(Node *head) 20 | { 21 | //Write your code here 22 | if(head == NULL) return; 23 | 24 | printReverse(head->next); 25 | 26 | cout << head->data << " "; 27 | } 28 | -------------------------------------------------------------------------------- /Linked List/Print ith node.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************** 2 | 3 | Following is the class structure of the Node class: 4 | 5 | class Node 6 | { 7 | public: 8 | int data; 9 | Node *next; 10 | Node(int data) 11 | { 12 | this->data = data; 13 | this->next = NULL; 14 | } 15 | }; 16 | 17 | *****************************************************************/ 18 | 19 | void printIthNode(Node *head, int i) 20 | { 21 | //Write your code here 22 | int count = 0; 23 | Node* current = head; 24 | while(current != NULL) { 25 | if(count == i) 26 | cout << (current->data); 27 | count++; 28 | current = current -> next; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Linked List/kReverse.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************** 2 | 3 | Following is the class structure of the Node class: 4 | 5 | class Node 6 | { 7 | public: 8 | int data; 9 | Node *next; 10 | Node(int data) 11 | { 12 | this->data = data; 13 | this->next = NULL; 14 | } 15 | }; 16 | 17 | *****************************************************************/ 18 | 19 | Node *kReverse(Node *head, int k) 20 | { 21 | //Write your code here 22 | if(k == 0 || k == 1) { 23 | return head; 24 | } 25 | Node* current = head; 26 | Node* fwd = NULL; 27 | Node* prev = NULL; 28 | 29 | int count = 0; 30 | while(count < k && current != NULL) { 31 | fwd = current->next; 32 | current->next = prev; 33 | prev = current; 34 | current = fwd; 35 | count++; 36 | } 37 | if(fwd != NULL) { 38 | head->next = kReverse(fwd, k); 39 | } 40 | return prev; 41 | } 42 | -------------------------------------------------------------------------------- /Priority Queue/1464. Maximum Product of Two Elements in an Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProduct(vector& nums) { 4 | priority_queuepq; 5 | for(int i : nums) 6 | pq.push(i); 7 | int x = pq.top(); 8 | pq.pop(); 9 | int y = pq.top(); 10 | return (x - 1) * (y - 1); 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /Priority Queue/1642. Furthest Building You Can Reach.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int furthestBuilding(vector& h, int b, int l) { 4 | 5 | // Priority Queue for storing the bricks used in each step in decreasing order (Max at top) 6 | priority_queue p; 7 | 8 | int i=0, diff =0; 9 | for(i=0; is1, s2; 4 | MyQueue() { 5 | 6 | } 7 | 8 | void push(int x) { 9 | s1.push(x); 10 | } 11 | 12 | int pop() { 13 | int val = peek(); 14 | s2.pop(); 15 | return val; 16 | } 17 | 18 | int peek() { 19 | if(s2.empty()) { 20 | while(s1.empty() == false) { 21 | s2.push(s1.top()); 22 | s1.pop(); 23 | } 24 | } 25 | return s2.top(); 26 | } 27 | 28 | bool empty() { 29 | return s1.empty() && s2.empty(); 30 | } 31 | }; 32 | 33 | /** 34 | * Your MyQueue object will be instantiated and called as such: 35 | * MyQueue* obj = new MyQueue(); 36 | * obj->push(x); 37 | * int param_2 = obj->pop(); 38 | * int param_3 = obj->peek(); 39 | * bool param_4 = obj->empty(); 40 | */ 41 | -------------------------------------------------------------------------------- /Queue/950. Reveal Cards In Increasing Order.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector deckRevealedIncreasing(vector& deck) { 4 | 5 | int n = deck.size(); 6 | std::sort(deck.begin(), deck.end()); 7 | std::deque st; 8 | st.push_front(deck[n - 1]); 9 | for (int i = n - 2; i >= 0; i--) { 10 | st.push_front(st.back()); 11 | st.pop_back(); 12 | st.push_front(deck[i]); 13 | } 14 | std::vector revealed; 15 | for (int i = 0; i < n; i++) { 16 | revealed.push_back(st.front()); 17 | st.pop_front(); 18 | } 19 | return revealed; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Queue/Check redundant brackets.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | bool checkRedundantBrackets(string expression) { 3 | // Write your code here 4 | stackstk; 5 | string operators = "+-*/"; 6 | 7 | for(int i = 0; i < expression.length(); ++i) { 8 | if(expression[i] == '(' || operators.find(expression[i]) != string::npos) { 9 | stk.push(expression[i]); 10 | }else if(expression[i] == ')') { 11 | bool hasOperator = false; 12 | 13 | while(!stk.empty() && stk.top() != '(') { 14 | stk.pop(); 15 | hasOperator = true; 16 | } 17 | 18 | if(!hasOperator) { 19 | return true; 20 | } 21 | 22 | if(!stk.empty()) { 23 | stk.pop(); 24 | } 25 | } 26 | } 27 | return false; 28 | } 29 | -------------------------------------------------------------------------------- /Queue/Reverse Queue.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | void reverseQueue(queue &input) { 3 | // Write your code here 4 | 5 | if(input.size() <= 1) { 6 | return; 7 | } 8 | 9 | int front = input.front(); 10 | input.pop(); 11 | 12 | reverseQueue(input); 13 | 14 | input.push(front); 15 | } 16 | -------------------------------------------------------------------------------- /Recursion/231. Power of Two.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPowerOfTwo(int n) { 4 | if(n <= 0) return false; 5 | return (n & (n - 1)) == 0; // Checks if only one bit is set 6 | } 7 | }; 8 | -------------------------------------------------------------------------------- /Recursion/509-Fibonacci-Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int fib(int n) { 4 | if(n <= 1) return n; 5 | return fib(n - 1) + fib(n - 2); 6 | } 7 | }; 8 | -------------------------------------------------------------------------------- /Recursion/78-Subsets.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> subsets(vector& nums) { 4 | int n = nums.size(); 5 | vector>ans; 6 | for(int i = 0; i < (1 << n); i++) { 7 | vectort; 8 | for(int j = 0; j < n; j++) { 9 | if(i & (1 << j)) { 10 | t.push_back(nums[j]); 11 | } 12 | } 13 | ans.push_back(t); 14 | } 15 | sort(ans.begin(), ans.end()); 16 | return ans; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Recursion/Factorial.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | class Solution{ 7 | public: 8 | long long int factorial(int N){ 9 | //code here 10 | if(N == 0) 11 | return 1; 12 | return N * factorial(N - 1); 13 | } 14 | }; 15 | 16 | // { Driver Code Starts. 17 | int main() 18 | { 19 | int t; 20 | cin>>t; 21 | while(t--) 22 | { 23 | int N; 24 | cin>>N; 25 | Solution ob; 26 | cout << ob.factorial(N) << endl; 27 | } 28 | return 0; 29 | } // } Driver Code Ends 30 | -------------------------------------------------------------------------------- /Recursion/Josephus-problem.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | //Initial Template for C 3 | 4 | #include 5 | 6 | 7 | // } Driver Code Ends 8 | //User function Template for C 9 | 10 | int josephus(int n, int k) 11 | { 12 | //Your code here 13 | if(n == 1) 14 | return 1; 15 | else 16 | return (josephus(n - 1, k)+ k - 1) % n + 1; 17 | } 18 | 19 | //{ Driver Code Starts. 20 | 21 | int main() { 22 | 23 | int t; 24 | scanf("%d", &t);//testcases 25 | while(t--) 26 | { 27 | int n,k; 28 | scanf("%d%d", &n, &k);//taking input n and k 29 | 30 | //calling josephus() function 31 | printf("%d\n", josephus(n,k)); 32 | } 33 | return 0; 34 | } 35 | // } Driver Code Ends 36 | -------------------------------------------------------------------------------- /Recursion/Nth-Fibonacci-Number.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | // Initial Template for C++ 3 | #include 4 | using namespace std; 5 | 6 | // } Driver Code Ends 7 | // User function Template for C++ 8 | class Solution { 9 | public: 10 | long long int nthFibonacci(long long int n){ 11 | // code here 12 | int mod = 1000000007; 13 | 14 | int a = 0, b = 1, curr; 15 | for(int i = 2; i <= n; i++) 16 | { 17 | curr = (a % mod + b % mod) % mod; 18 | a = b; 19 | b = curr; 20 | } 21 | return curr; 22 | } 23 | }; 24 | 25 | // { Driver Code Starts. 26 | int main() { 27 | int t; 28 | cin >> t; 29 | while (t--) { 30 | long long int n; 31 | cin >> n; 32 | Solution ob; 33 | cout << ob.nthFibonacci(n) << endl; 34 | } 35 | return 0; 36 | } 37 | // } Driver Code Ends 38 | -------------------------------------------------------------------------------- /Recursion/Print-1-To-N-Without-Loop.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | 6 | // } Driver Code Ends 7 | class Solution{ 8 | public: 9 | //Complete this function 10 | void printNos(int N) 11 | { 12 | //Your code here 13 | if ( N == 0) return; 14 | printNos(N - 1); 15 | cout << N << " "; 16 | } 17 | }; 18 | 19 | // { Driver Code Starts. 20 | /* Driver program to test printNos */ 21 | int main() 22 | { 23 | int T; 24 | 25 | //taking testcases 26 | cin>>T; 27 | 28 | while(T--) 29 | { 30 | int N; 31 | 32 | //input N 33 | cin>>N; 34 | Solution ob; 35 | //calling printNos() function 36 | ob.printNos(N); 37 | cout << "\n"; 38 | } 39 | return 0; 40 | } 41 | // } Driver Code Ends 42 | -------------------------------------------------------------------------------- /Recursion/Print-1-to-n-without-using-loops.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | //User function Template for C++ 7 | class Solution 8 | { 9 | public: 10 | void printTillN(int N) 11 | { 12 | // Write Your Code here 13 | if(N == 0) return; 14 | printTillN(N - 1); 15 | cout << N << " "; 16 | } 17 | }; 18 | 19 | // { Driver Code Starts. 20 | int main() 21 | { 22 | int t; 23 | cin >> t; 24 | while (t--) 25 | { 26 | int N; 27 | cin>>N; 28 | Solution ob; 29 | ob.printTillN(N); 30 | cout< 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | class Solution{ 7 | public: 8 | int fib(int N){ 9 | //code here 10 | if(N <= 1) return N; 11 | int a = 0, b = 1, c; 12 | for(int i = 2; i <= N; i ++) { 13 | c = (a+b) % 10; 14 | a = b, b = c; 15 | } 16 | return c; 17 | } 18 | }; 19 | 20 | // { Driver Code Starts. 21 | int main() 22 | { 23 | int t; 24 | cin>>t; 25 | while(t--) 26 | { 27 | int N; 28 | cin>>N; 29 | Solution ob; 30 | cout << ob.fib(N) << endl; 31 | } 32 | return 0; 33 | } // } Driver Code Ends 34 | -------------------------------------------------------------------------------- /Searching/278. First Bad Version.cpp: -------------------------------------------------------------------------------- 1 | // The API isBadVersion is defined for you. 2 | // bool isBadVersion(int version); 3 | 4 | class Solution { 5 | public: 6 | int firstBadVersion(int n) { 7 | int left = 1; 8 | int right = n; 9 | 10 | while (left < right) { 11 | int mid = left + (right - left) / 2; 12 | 13 | if (isBadVersion(mid)) { 14 | 15 | right = mid; 16 | } else { 17 | 18 | left = mid + 1; 19 | } 20 | } 21 | 22 | // When the loop exits, left will point to the first bad version. 23 | return left; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Searching/35. Search Insert Position.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int searchInsert(vector& nums, int target) { 4 | int low = 0; 5 | int high = nums.size() - 1; 6 | while(low <= high) { 7 | int mid = (low + high) / 2; 8 | if(nums[mid] == target) 9 | return mid; 10 | else if(nums[mid] < target) 11 | low = mid + 1; 12 | else 13 | high = mid - 1; 14 | } 15 | return low; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Searching/540-Single-Element-in-a-Sorted-Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int singleNonDuplicate(vector& nums) { 4 | // int res = 0; 5 | // for(int i = 0; i < nums.size(); i++) { 6 | // res ^= nums[i]; 7 | // } 8 | // return res; 9 | 10 | int low = 0, high = nums.size() - 2; 11 | 12 | while(low <= high) { 13 | int mid = (low+high)/2; 14 | if(nums[mid] == nums[mid^1]){ 15 | low = mid + 1; 16 | }else { 17 | high = mid - 1; 18 | } 19 | } 20 | return nums[low]; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Searching/69-Sqrt(x).cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int mySqrt(int x) { 4 | 5 | //using pre build function 6 | //return sqrt(x); 7 | 8 | //using binary search 9 | long long s = 1, e = INT_MAX; 10 | 11 | long long ans = 0; 12 | 13 | while(s <= e) { 14 | long long m = (s+e)/2; 15 | 16 | if(m*m <= x) { 17 | s = m + 1; 18 | ans = m; 19 | } else { 20 | e = m - 1; 21 | } 22 | } 23 | return ans; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Searching/704. Binary Search.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int search(vector& nums, int target) { 4 | int low = 0; 5 | int high = nums.size() - 1; 6 | while(low <= high) { 7 | int mid = (low + high) / 2; 8 | if(nums[mid] == target) 9 | return mid; 10 | else if(nums[mid] < target) 11 | low = mid + 1; 12 | else 13 | high = mid - 1; 14 | } 15 | return -1; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Searching/744. Find Smallest Letter Greater Than Target.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | char nextGreatestLetter(vector& letters, char target) { 4 | int n = letters.size(); 5 | int low = 0; 6 | int high = n - 1; 7 | int ans = letters[0]; 8 | while(low <= high) { 9 | int mid = (low + high) / 2; 10 | if(letters[mid] <= target) { 11 | low = mid + 1; 12 | }else { 13 | ans = letters[mid]; 14 | high = mid - 1; 15 | } 16 | } 17 | return ans; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Searching/First-and-last-occurrences-of-x.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | vector find(int arr[], int n , int x ) 7 | { 8 | // code here 9 | //using linear search 10 | vector ans; 11 | for(int i = 0; i < n ; i++) { 12 | if(arr[i] == x) 13 | ans.push_back(i); 14 | } 15 | if(ans.size() == 0) 16 | return {-1, -1}; 17 | else 18 | return {ans[0], ans[ans.size() - 1]}; 19 | } 20 | 21 | //{ Driver Code Starts. 22 | 23 | int main() 24 | { 25 | int t; 26 | cin>>t; 27 | while(t--) 28 | { 29 | int n,x; 30 | cin>>n>>x; 31 | int arr[n],i; 32 | for(i=0;i>arr[i]; 34 | vector ans; 35 | ans=find(arr,n,x); 36 | cout<& nums, int minK, int maxK) { 4 | long long res = 0; 5 | int bad_idx = -1, left_idx = -1, right_idx = -1; 6 | 7 | for(int i = 0; i < nums.size(); ++i) { 8 | if(!(minK <= nums[i] && nums[i] <= maxK)) { 9 | bad_idx = i; 10 | } 11 | 12 | if(nums[i] == minK) { 13 | left_idx = i; 14 | } 15 | 16 | if(nums[i] == maxK) { 17 | right_idx = i; 18 | } 19 | 20 | res += max(0, min(left_idx, right_idx) - bad_idx); 21 | } 22 | 23 | return res; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Sliding Window/713. Subarray Product Less Than K.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numSubarrayProductLessThanK(vector& nums, int k) { 4 | int left = 0, right = 0, product = 1, count = 0; 5 | int n = nums.size(); 6 | if(k <= 1) return 0; 7 | while (right < n) { 8 | product *= nums[right]; 9 | while (product >= k) product /= nums[left++]; 10 | count += 1 + (right - left); 11 | right++; 12 | } 13 | return count; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Sorting/Sort String.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | int main() 5 | { 6 | //cout<<"I am a Software Engineer"<> t; 9 | while(t--) { 10 | string s; 11 | cin >> s; 12 | sort(s.begin(), s.end()); 13 | cout << s << endl; 14 | } 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /Sorting/Sort The Array.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | class Solution{ 7 | public: 8 | vector sortArr(vectorarr, int n){ 9 | //complete the function here 10 | sort(arr.begin(), arr.end()); 11 | return arr; 12 | } 13 | }; 14 | 15 | //{ Driver Code Starts. 16 | int main(){ 17 | 18 | int t; 19 | cin >> t; 20 | while(t--){ 21 | int n; 22 | cin >> n; 23 | vectors(n); 24 | for(int i = 0; i < n; i++) 25 | cin >> s[i]; 26 | Solution ob; 27 | vectorv = ob.sortArr(s, n); 28 | for(auto i : v) 29 | cout << i << ' '; 30 | cout << endl; 31 | } 32 | return 0; 33 | } 34 | 35 | 36 | // } Driver Code Ends 37 | -------------------------------------------------------------------------------- /Stack/150. Evaluate Reverse Polish Notation.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int evalRPN(vector& tokens) { 4 | stackst; 5 | for(auto x : tokens) { 6 | if(x == "+" || x == "-" || x == "*" || x == "/") { 7 | int operand2 = st.top(); 8 | st.pop(); 9 | int operand1 = st.top(); 10 | st.pop(); 11 | 12 | if(x == "+") { 13 | st.push(operand1 + operand2); 14 | } 15 | 16 | if(x == "-") { 17 | st.push(operand1 - operand2); 18 | } 19 | 20 | if(x == "*") { 21 | st.push(operand1 * operand2); 22 | } 23 | 24 | if(x == "/") { 25 | st.push(operand1 / operand2); 26 | } 27 | } 28 | else { 29 | stringstream ss(x); 30 | int data; 31 | ss >> data; 32 | st.push(data); 33 | } 34 | } 35 | return st.top(); 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /Stack/155. Min Stack.cpp: -------------------------------------------------------------------------------- 1 | class MinStack { 2 | public: 3 | stacks1, s2; 4 | MinStack() { 5 | 6 | } 7 | 8 | void push(int val) { 9 | if(s2.empty() || val <= s2.top()) { 10 | s2.push(val); 11 | } 12 | s1.push(val); 13 | } 14 | 15 | void pop() { 16 | if(s1.top() == s2.top()) { 17 | s2.pop(); 18 | } 19 | s1.pop(); 20 | } 21 | 22 | int top() { 23 | return s1.top(); 24 | } 25 | 26 | int getMin() { 27 | return s2.top(); 28 | } 29 | }; 30 | 31 | /** 32 | * Your MinStack object will be instantiated and called as such: 33 | * MinStack* obj = new MinStack(); 34 | * obj->push(val); 35 | * obj->pop(); 36 | * int param_3 = obj->top(); 37 | * int param_4 = obj->getMin(); 38 | */ 39 | -------------------------------------------------------------------------------- /Stack/225. Implement Stack using Queues.cpp: -------------------------------------------------------------------------------- 1 | class MyStack { 2 | public: 3 | queueq1, q2; 4 | MyStack() { 5 | 6 | } 7 | 8 | void push(int x) { 9 | //q1 -> q2 10 | while(!q1.empty()) { 11 | q2.push(q1.front()); 12 | q1.pop(); 13 | } 14 | 15 | // q1 push x 16 | q1.push(x); 17 | 18 | while(!q2.empty()) { 19 | q1.push(q2.front()); 20 | q2.pop(); 21 | } 22 | } 23 | 24 | int pop() { 25 | int val = q1.front(); 26 | q1.pop(); 27 | return val; 28 | } 29 | 30 | int top() { 31 | return q1.front(); 32 | } 33 | 34 | bool empty() { 35 | return q1.empty(); 36 | } 37 | }; 38 | 39 | /** 40 | * Your MyStack object will be instantiated and called as such: 41 | * MyStack* obj = new MyStack(); 42 | * obj->push(x); 43 | * int param_2 = obj->pop(); 44 | * int param_3 = obj->top(); 45 | * bool param_4 = obj->empty(); 46 | */ 47 | -------------------------------------------------------------------------------- /Stack/456. 132 Pattern.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool find132pattern(vector& nums) { 4 | int n = nums.size(); 5 | if (n < 3) return false; 6 | 7 | std::vector minValues(n); 8 | minValues[0] = nums[0]; 9 | 10 | for (int i = 1; i < n; i++) { 11 | minValues[i] = std::min(minValues[i - 1], nums[i]); 12 | } 13 | 14 | std::stack s; 15 | 16 | for (int j = n - 1; j >= 0; j--) { 17 | if (nums[j] > minValues[j]) { 18 | while (!s.empty() && s.top() <= minValues[j]) { 19 | s.pop(); 20 | } 21 | if (!s.empty() && s.top() < nums[j]) { 22 | return true; 23 | } 24 | s.push(nums[j]); 25 | } 26 | } 27 | 28 | return false; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Stack/496. Next Greater Element I.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector nextGreaterElement(vector& nums1, vector& nums2) { 4 | unordered_mapumap; 5 | int n = nums2.size(); 6 | stackst; 7 | for(int i = n - 1; i >= 0; i--) { 8 | int ele = nums2[i]; 9 | while(!st.empty() && st.top() < ele) { 10 | st.pop(); 11 | } 12 | int res = (st.empty() ? -1 : st.top()); 13 | umap.insert({ele, res}); 14 | st.push(ele); 15 | } 16 | vectorans; 17 | for(auto x : nums1) { 18 | ans.push_back(umap[x]); 19 | } 20 | return ans; 21 | } 22 | }; 23 | 24 | -------------------------------------------------------------------------------- /Stack/901. Online Stock Span.cpp: -------------------------------------------------------------------------------- 1 | class StockSpanner { 2 | public: 3 | stack>s; 4 | StockSpanner() { 5 | 6 | } 7 | 8 | int next(int price) { 9 | int span = 1; 10 | while(!s.empty() && s.top().first <= price) { 11 | span += s.top().second; 12 | s.pop(); 13 | } 14 | s.push({price, span}); 15 | return span; 16 | } 17 | }; 18 | 19 | /** 20 | * Your StockSpanner object will be instantiated and called as such: 21 | * StockSpanner* obj = new StockSpanner(); 22 | * int param_1 = obj->next(price); 23 | */ 24 | -------------------------------------------------------------------------------- /Stack/Reverse a Stack.cpp: -------------------------------------------------------------------------------- 1 | void reverseStack(stack &input, stack &extra) { 2 | //Write your code here 3 | if(input.size() <= 1) { 4 | return; 5 | } 6 | 7 | int lastElement = input.top(); 8 | input.pop(); 9 | 10 | reverseStack(input, extra); 11 | 12 | while(!input.empty()) { 13 | int top = input.top(); 14 | input.pop(); 15 | extra.push(top); 16 | } 17 | 18 | input.push(lastElement); 19 | 20 | while(!extra.empty()) { 21 | int top = extra.top(); 22 | extra.pop(); 23 | input.push(top); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Stack/Sort a Stack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void insertInDescendingOrder(std::stack& stack, int element) { 4 | if (stack.empty() || element > stack.top()) { 5 | stack.push(element); 6 | return; 7 | } 8 | 9 | int topElement = stack.top(); 10 | stack.pop(); 11 | insertInDescendingOrder(stack, element); 12 | stack.push(topElement); 13 | } 14 | 15 | void sortStack(stack &stack) 16 | { 17 | // Write your code here 18 | if (!stack.empty()) { 19 | int topElement = stack.top(); 20 | stack.pop(); 21 | sortStack(stack); 22 | insertInDescendingOrder(stack, topElement); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /String/13. Roman to Integer.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int romanToInt(string s) { 4 | mapmp { 5 | {'I', 1}, 6 | {'V', 5}, 7 | {'X', 10}, 8 | {'L', 50}, 9 | {'C', 100}, 10 | {'D', 500}, 11 | {'M', 1000}, 12 | }; 13 | int value = 0; 14 | for(int i = 0; i < s.size(); i++) { 15 | if(mp[s[i]] < mp[s[i+1]]) 16 | value -= mp[s[i]]; 17 | else 18 | value += mp[s[i]]; 19 | } 20 | return value; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /String/14. Longest Common Prefix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string longestCommonPrefix(vector& strs) { 4 | if(strs.empty()) return ""; 5 | string prefix = strs[0]; 6 | for(string s : strs) { 7 | while(s.find(prefix) != 0) 8 | prefix = prefix.substr(0, prefix.length() - 1); 9 | } 10 | return prefix; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /String/1422. Maximum Score After Splitting a String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxScore(string s) { 4 | int length = s.size(); 5 | int low = 0; 6 | int temp = s[0] == '0' ? 1 : 0; 7 | int score = temp; 8 | for(int i = 1; i < length - 1; i++) { 9 | if(s[i] == '0') { 10 | temp += 1; 11 | }else { 12 | low++; 13 | temp -= 1; 14 | } 15 | 16 | if(temp > score) { 17 | score = temp; 18 | } 19 | } 20 | 21 | low += (s[length - 1] == '1' ? 1 : 0); 22 | 23 | return low + score; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /String/1544. Make The String Great.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | std::string makeGood(std::string s) { 4 | std::stack stack; 5 | 6 | for (char c : s) { 7 | if (!stack.empty() && std::abs(c - stack.top()) == 32) { 8 | stack.pop(); 9 | } else { 10 | stack.push(c); 11 | } 12 | } 13 | 14 | std::string result; 15 | while (!stack.empty()) { 16 | result = stack.top() + result; 17 | stack.pop(); 18 | } 19 | 20 | return result; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /String/1614. Maximum Nesting Depth of the Parentheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxDepth(string s) { 4 | int count = 0; 5 | int max_num = 0; 6 | for (char c : s) { 7 | if (c == '(') { 8 | count++; 9 | if (max_num < count) 10 | max_num = count; 11 | } else if (c == ')') { 12 | count--; 13 | } 14 | } 15 | return max_num; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /String/1624. Largest Substring Between Two Equal Characters.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxLengthBetweenEqualCharacters(string s) { 4 | int maxLength = -1; 5 | 6 | for (int i = 0; i < s.size(); i++) { 7 | for (int j = i + 1; j < s.size(); j++) { 8 | if (s[i] == s[j]) { 9 | maxLength = max(maxLength, j - i - 1); 10 | } 11 | } 12 | } 13 | 14 | return maxLength; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /String/1662. Check If Two String Arrays are Equivalent.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool arrayStringsAreEqual(vector& word1, vector& word2) { 4 | // string s1 = ""; 5 | // string s2 = ""; 6 | 7 | // for(const string& s : word1) { 8 | // s1 += s; 9 | // } 10 | 11 | // for(const string& s : word2) { 12 | // s2 += s; 13 | // } 14 | 15 | // return s1 == s2; 16 | // } 17 | 18 | string left; 19 | string right; 20 | for(int i = 0; i < word1.size(); i++) 21 | left += word1[i]; 22 | for(int i = 0; i < word2.size(); i++) 23 | right += word2[i]; 24 | return left == right; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /String/168. Excel Sheet Column Title.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string convertToTitle(int columnNumber) { 4 | string result = ""; 5 | while(columnNumber) { 6 | char c = 'A' + (columnNumber - 1) % 26; 7 | result = c + result; 8 | columnNumber = (columnNumber - 1) / 26; 9 | } 10 | return result; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /String/1704. Determine if String Halves Are Alike: -------------------------------------------------------------------------------- 1 | 2 | string vowels = "aeiouAEIOU"; 3 | class Solution { 4 | public: 5 | bool halvesAreAlike(string s) { 6 | int mid = s.size() / 2, ans = 0; 7 | for (int i = 0, j = mid; i < mid; i++, j++) { 8 | if (~vowels.find(s[i])) ans++; 9 | if (~vowels.find(s[j])) ans--; 10 | } 11 | return ans == 0; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /String/1758. Minimum Changes To Make Alternating Binary String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minOperations(string s) { 4 | int countForAlternate0 = 0; 5 | int countForAlternate1 = 0; 6 | 7 | for (int i = 0; i < s.size(); i++) { 8 | if (i % 2 == 0) { 9 | if (s[i] == '0') { 10 | countForAlternate1++; 11 | } else { 12 | countForAlternate0++; 13 | } 14 | } else { 15 | if (s[i] == '1') { 16 | countForAlternate1++; 17 | } else { 18 | countForAlternate0++; 19 | } 20 | } 21 | } 22 | 23 | return min(countForAlternate0, countForAlternate1); 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /String/1759. Count Number of Homogenous Substrings.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countHomogenous(string s) { 4 | int left = 0; 5 | long long res = 0; 6 | 7 | for(int i = 0; i < s.length(); i++) { 8 | if(s[left] == s[i]) { 9 | res += i - left + 1; 10 | }else { 11 | res += 1; 12 | left = i; 13 | } 14 | } 15 | return (int) (res % (1000000007)); 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /String/1897. Redistribute Characters to Make All Strings Equal.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool makeEqual(vector& words) { 4 | unordered_map counts; 5 | for (auto a : words) { 6 | for (char x : a) { 7 | counts[x]++; 8 | } 9 | } 10 | 11 | int n = words.size(); 12 | for (auto a : counts) { 13 | if (a.second % n != 0) { 14 | return false; 15 | } 16 | } 17 | 18 | return true; 19 | } 20 | }; 21 | 22 | -------------------------------------------------------------------------------- /String/1903. Largest Odd Number in String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string largestOddNumber(string num) { 4 | string result = ""; 5 | for(int i = num.size() - 1; i >= 0 ; i--) { 6 | if((num[i] - '0') % 2 == 1) { 7 | return num.substr(0, i + 1); 8 | } 9 | } 10 | return ""; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /String/1930. Unique Length-3 Palindromic Subsequences.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countPalindromicSubsequence(string s) { 4 | int n = s.size(); 5 | int count = 0; 6 | 7 | for (char c = 'a'; c <= 'z'; ++c) { 8 | int first = -1, last = -1; 9 | 10 | for (int i = 0; i < n; ++i) { 11 | if (s[i] == c) { 12 | if (first == -1) { 13 | first = i; 14 | } 15 | last = i; 16 | } 17 | } 18 | 19 | if (first != -1) { 20 | unordered_set uniqueChars; 21 | 22 | for (int i = first + 1; i < last; ++i) { 23 | uniqueChars.insert(s[i]); 24 | } 25 | 26 | count += uniqueChars.size(); 27 | } 28 | } 29 | 30 | return count; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /String/2108. Find First Palindromic String in the Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string firstPalindrome(vector& words) { 4 | for(int i = 0 ; i < words.size() ; i++) 5 | { 6 | int flag = 0; 7 | int n = words[i].size(); 8 | for(int j = 0 ; j < n/2 ; j++) 9 | { 10 | if(words[i][j] != words[i][n-j-1]) 11 | { 12 | flag = 1; 13 | break; 14 | } 15 | } 16 | if(flag == 0) 17 | return words[i]; 18 | 19 | } 20 | return ""; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /String/2264. Largest 3-Same-Digit Number in String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string largestGoodInteger(string num) { 4 | int result = -1; 5 | for(int i = 0; i + 2 < num.length(); i++) { 6 | if(num[i] == num[i + 1] && num[i] == num[i + 2]) { 7 | result = max(result, num[i] - '0'); 8 | } 9 | } 10 | return (result == -1) ? "" : string(3, '0' + result); 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /String/242. Valid Anagram.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isAnagram(string s, string t) { 4 | // vectorvec(26, 0); 5 | // if(s.length() != t.length()) return false; 6 | // for(int i = 0; i < s.length(); i++) { 7 | // vec[s[i] - 'a']++; 8 | // vec[t[i] - 'a']--; 9 | // } 10 | // for(int i = 0; i < 26; i++) { 11 | // if(vec[i] != 0) 12 | // return false; 13 | // } 14 | // return true; 15 | mapmp; 16 | if(s.length() != t.length()) return false; 17 | for(char c : s) { 18 | mp[c]++; 19 | } 20 | for(char c : t) { 21 | mp[c]--; 22 | } 23 | for(auto k : mp) { 24 | if(k.second > 0) 25 | return false; 26 | } 27 | return true; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /String/2707. Extra Characters in a String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minExtraChar(string s, vector& dictionary) { 4 | int max_val = s.length() + 1; 5 | vector dp(s.length() + 1, max_val); 6 | dp[0] = 0; 7 | 8 | unordered_set dictionary_set(dictionary.begin(), dictionary.end()); 9 | 10 | for (int i = 1; i <= s.length(); ++i) { 11 | dp[i] = dp[i - 1] + 1; 12 | for (int l = 1; l <= i; ++l) { 13 | if (dictionary_set.find(s.substr(i - l, l)) != dictionary_set.end()) { 14 | dp[i] = min(dp[i], dp[i - l]); 15 | } 16 | } 17 | } 18 | return dp.back(); 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /String/2785. Sort Vowels in a String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string sortVowels(string s) { 4 | // Step 1: Collect vowels and sort them in descending order 5 | vector vowels; 6 | for (char c : s) { 7 | if (string("aeiouAEIOU").find(c) != string::npos) { 8 | vowels.push_back(c); 9 | } 10 | } 11 | sort(vowels.begin(), vowels.end(), greater()); 12 | 13 | // Step 2: Construct the answer string by replacing vowels in sorted order 14 | string result; 15 | for (char c : s) { 16 | if (string("aeiouAEIOU").find(c) != string::npos) { 17 | result += vowels.back(); 18 | vowels.pop_back(); 19 | } else { 20 | result += c; 21 | } 22 | } 23 | 24 | // Step 3: Return the final string 25 | return result; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /String/28. Find the Index of the First Occurrence in a String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int strStr(string haystack, string needle) { 4 | // return haystack.find(needle); 5 | for(int i = 0; i < haystack.length(); i++) { 6 | if(haystack[i] == needle[0]) { 7 | int i1 = i+1; 8 | int j = 1; 9 | while(haystack[i] && needle[j]) { 10 | if(haystack[i1] != needle[j]) break; 11 | i1++; 12 | j++; 13 | } 14 | if(j == needle.length()) return i; 15 | } 16 | } 17 | return -1; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /String/344-Reverse-String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void reverseString(vector& s) { 4 | //reverse(s.begin(), s.end()); 5 | int r = s.size() - 1; 6 | int l = 0; 7 | while(l < r) { 8 | swap(s[l], s[r]); 9 | l++; 10 | r--; 11 | } 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /String/387. First Unique Character in a String.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public: 4 | int firstUniqChar(string s) { 5 | unordered_map mp; 6 | 7 | for (auto a : s) mp[a]++; 8 | for (int i = 0; i < s.size(); i++)if(mp[s[i]] == 1)return i; 9 | 10 | return -1; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /String/389. Find the Difference.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | char findTheDifference(string s, string t) { 4 | sort(s.begin(), s.end()); 5 | sort(t.begin(), t.end()); 6 | 7 | int i = 0, j = 0; 8 | while(i < s.size() && j < t.size()) { 9 | if(s[i] != t[j]){ 10 | return t[j]; 11 | } 12 | i++; 13 | j++; 14 | } 15 | return t[j]; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /String/392. Is Subsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isSubsequence(string s, string t) { 4 | if (s == "") return true; 5 | int j = 0; 6 | for(int i = 0; i < t.size(); i++) { 7 | if(t[i] == s[j]) 8 | j++; 9 | if(j == s.size()) 10 | return true; 11 | } 12 | return false; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /String/451. Sort Characters By Frequency.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string frequencySort(string s) { 4 | unordered_map counter; 5 | 6 | for(char c : s){ 7 | counter[c]++; 8 | } 9 | 10 | sort(s.begin(), s.end(), 11 | [&counter](const char a, const char b){ 12 | return (counter[a] == counter[b]) ? a < b : counter[a] > counter[b]; 13 | }); 14 | 15 | return s; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /String/49. Group Anagrams.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> groupAnagrams(vector& strs) { 4 | unordered_map> umap; 5 | for(auto x : strs) { 6 | string word = x; 7 | sort(word.begin(), word.end()); 8 | umap[word].push_back(x); 9 | } 10 | 11 | vector> result; 12 | for(auto x : umap) { 13 | result.push_back(x.second); 14 | } 15 | return result; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /String/58. Length of Last Word.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lengthOfLastWord(string s) { 4 | int count = 0; 5 | int flag = 0; 6 | for(int i = s.length() - 1; i >= 0; i--) { 7 | if(s[i] == ' ' && flag) { 8 | break; 9 | } 10 | if(s[i] != ' ') { 11 | flag = 1; 12 | count++; 13 | } 14 | } 15 | return count; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /String/647. Palindromic Substrings.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | private: 4 | string t; 5 | int check(int l, int r, int ans = 0) 6 | { 7 | while(l >= 0 and r <= t.size()) 8 | { 9 | if(t[l--] == t[r++]) ans++; 10 | else break; 11 | } 12 | return ans; 13 | } 14 | public: 15 | int countSubstrings(string s) 16 | { 17 | int n = size(s), ans = 0;t = s; 18 | for(int i = 0; i < n; i++) 19 | { 20 | ans += check(i,i); // odd length palindromes 21 | ans += check(i,i+1); // even length palindromes 22 | } 23 | return ans; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /String/C++ Strings.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | string conCat(string a , string b); 7 | 8 | int main() 9 | { 10 | int t; 11 | cin>>t; 12 | while(t--) 13 | { 14 | string a,b; 15 | cin>>a>>b; 16 | cout< 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | 7 | class Solution 8 | { 9 | public: 10 | int getCount (string S, int N) 11 | { 12 | //code here. 13 | mapmp; 14 | for(int i = 0; i < S.size(); i++) { 15 | if(S[i] != S[i - 1]) 16 | mp[S[i]]++; 17 | } 18 | int count = 0; 19 | for(auto it:mp) { 20 | if(it.second == N) 21 | count++; 22 | } 23 | return count; 24 | } 25 | }; 26 | 27 | //{ Driver Code Starts. 28 | int main() 29 | { 30 | int t; cin >> t; 31 | while (t--) 32 | { 33 | string s; cin >> s; 34 | int n; cin >> n; 35 | 36 | Solution ob; 37 | cout < 5 | using namespace std; 6 | 7 | 8 | // } Driver Code Ends 9 | //User function Template for C++ 10 | 11 | class Solution{ 12 | public: 13 | string longest(string names[], int n) 14 | { 15 | string res = names[0]; 16 | 17 | for(int i = 0; i < n; i++) { 18 | if(names[i].size() > res.size()) 19 | res = names[i]; 20 | } 21 | return res; 22 | } 23 | }; 24 | 25 | //{ Driver Code Starts. 26 | 27 | int main() 28 | { 29 | int t; 30 | cin>>t; 31 | while(t--) 32 | { 33 | int n; 34 | cin>>n; 35 | string names[n]; 36 | 37 | for(int i=0;i>names[i]; 39 | Solution ob; 40 | cout<< ob.longest(names, n) << endl; 41 | } 42 | } 43 | 44 | // } Driver Code Ends 45 | -------------------------------------------------------------------------------- /String/Palindrome-String.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | 3 | #include 4 | using namespace std; 5 | 6 | 7 | // } Driver Code Ends 8 | //User function template for C++ 9 | class Solution{ 10 | public: 11 | 12 | 13 | int isPalindrome(string S) 14 | { 15 | // Your code goes here 16 | int r = S.size(); 17 | int start = 0, end = (r - 1); 18 | while(start <= end) { 19 | if(S[start] != S[end]){ 20 | return 0; 21 | } 22 | else{ 23 | start++; 24 | end--; 25 | } 26 | } 27 | return 1; 28 | } 29 | 30 | }; 31 | 32 | // { Driver Code Starts. 33 | 34 | int main() 35 | { 36 | ios_base::sync_with_stdio(0); 37 | cin.tie(NULL); 38 | cout.tie(NULL); 39 | 40 | int t; 41 | cin >> t; 42 | while(t--) 43 | { 44 | string s; 45 | cin >> s; 46 | 47 | Solution ob; 48 | 49 | cout << ob.isPalindrome(s) << "\n"; 50 | } 51 | 52 | return 0; 53 | } // } Driver Code Ends 54 | -------------------------------------------------------------------------------- /String/Remove Spaces.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | class Solution 7 | { 8 | public: 9 | string modify (string s) 10 | { 11 | //code here. 12 | for(int i = 0; i < s.size(); i++) { 13 | if(s[i] == ' ') { 14 | s[i] = '\0'; 15 | } 16 | } 17 | return s; 18 | } 19 | }; 20 | 21 | //{ Driver Code Starts. 22 | int main() 23 | { 24 | int t; 25 | cin >> t; 26 | cin.ignore (); 27 | while (t--) 28 | { 29 | string s; 30 | getline (cin, s); 31 | Solution ob; 32 | cout < 2 | string replaceSpaces(string &str){ 3 | // Write your code here. 4 | string result; 5 | for (char c : str) { 6 | if (c == ' ') { 7 | result += "@40"; 8 | } else { 9 | result += c; 10 | } 11 | } 12 | return result; 13 | } 14 | -------------------------------------------------------------------------------- /String/Reverse a String.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | // Initial Template for C++ 3 | #include 4 | using namespace std; 5 | 6 | // } Driver Code Ends 7 | // User function Template for C++ 8 | class Solution { 9 | public: 10 | string revStr(string S) { 11 | // code here 12 | // reverse(S.begin(), S.end()); 13 | // return S; 14 | 15 | int s = 0, e = S.length() - 1; 16 | while(s < e) { 17 | swap(S[s], S[e]); 18 | s++; 19 | e--; 20 | } 21 | return S; 22 | } 23 | }; 24 | 25 | //{ Driver Code Starts. 26 | int main() { 27 | int t; 28 | cin >> t; 29 | while (t--) { 30 | string S; 31 | cin >> S; 32 | Solution ob; 33 | cout << ob.revStr(S) << endl; 34 | } 35 | return 0; 36 | } 37 | 38 | // } Driver Code Ends 39 | -------------------------------------------------------------------------------- /String/Reverse-a-String.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | //Initial Template for C++ 3 | 4 | 5 | #include 6 | using namespace std; 7 | 8 | 9 | string reverseWord(string str); 10 | 11 | 12 | int main() { 13 | 14 | int t; 15 | cin>>t; 16 | while(t--) 17 | { 18 | string s; 19 | cin >> s; 20 | 21 | cout << reverseWord(s) << endl; 22 | } 23 | return 0; 24 | 25 | } 26 | 27 | 28 | // } Driver Code Ends 29 | 30 | 31 | //User function Template for C++ 32 | 33 | string reverseWord(string str){ 34 | 35 | //Your code here 36 | // reverse(str.begin(), str.end()); 37 | // return str; 38 | 39 | 40 | int s = 0, e = str.length() - 1; 41 | while(s < e) { 42 | swap(str[s], str[e]); 43 | s++; 44 | e--; 45 | } 46 | return str; 47 | } 48 | 49 | -------------------------------------------------------------------------------- /String/Sort String.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | int main() 5 | { 6 | //cout<<"I am a Software Engineer"<> t; 9 | while(t--) { 10 | string s; 11 | cin >> s; 12 | sort(s.begin(), s.end()); 13 | cout << s << endl; 14 | } 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /String/String comparison.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | 6 | int stringComparsion(string s1, string s2); 7 | 8 | 9 | int main() 10 | { 11 | 12 | 13 | ios_base::sync_with_stdio(0); 14 | cin.tie(NULL); 15 | cout.tie(NULL); 16 | 17 | int t; 18 | cin >> t; 19 | while(t--) 20 | { 21 | string s1, s2; 22 | cin >> s1 >> s2; 23 | 24 | 25 | cout << stringComparsion(s1, s2) << "\n"; 26 | } 27 | 28 | return 0; 29 | } 30 | 31 | // } Driver Code Ends 32 | 33 | 34 | 35 | int stringComparsion(string s1,string s2) 36 | { 37 | // Your code goes here 38 | if(s1 == s2) return 0; 39 | 40 | int i = 0, j = 0; 41 | while(s1[i] != '\0' || s2[j] != '\0') { 42 | if(s1[i] > s2[j]) return 1; 43 | if(s1[i] < s2[j]) return -1; 44 | if(s1[i] == 'n' && s1[i + 1] == 'g' && s2[j + 1] != 'g') return 1; 45 | if(s2[j] == 'n' && s2[j + 1] == 'g' && s1[i + 1] != 'g') return -1; 46 | i++; 47 | j++; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Tree/100. Same Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | bool isSameTree(TreeNode* p, TreeNode* q) { 15 | if(p == NULL && q == NULL) { 16 | return true; 17 | } 18 | if(p == NULL || q == NULL) { 19 | return false; 20 | } 21 | if(p->val != q->val) { 22 | return false; 23 | } 24 | return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Tree/101. Symmetric Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | bool isSymmetric(TreeNode* root) { 15 | return root == NULL || isSymmetricChecker(root->left, root->right); 16 | } 17 | bool isSymmetricChecker(TreeNode* left, TreeNode* right) { 18 | if((left==NULL) || (right==NULL)) 19 | return left==right; 20 | 21 | if(left->val!=right->val) return false; 22 | 23 | return isSymmetricChecker(left->left, right->right) 24 | && 25 | isSymmetricChecker(left->right, right->left); 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Tree/104. Maximum Depth of Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | int maxDepth(TreeNode* root) { 15 | if(root == NULL) { 16 | return 0; 17 | } 18 | return max(maxDepth(root->left), maxDepth(root->right)) + 1; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Tree/110. Balanced Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | 15 | int height(TreeNode* node) { 16 | if (node == NULL) { 17 | return 0; 18 | } 19 | return 1 + max(height(node->left), height(node->right)); 20 | } 21 | 22 | bool isBalanced(TreeNode* root) { 23 | if (root == NULL) { 24 | return true; 25 | } 26 | 27 | int leftHeight = height(root->left); 28 | int rightHeight = height(root->right); 29 | 30 | return abs(leftHeight - rightHeight) <= 1 && isBalanced(root->left) && isBalanced(root->right); 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /Tree/111. Minimum Depth of Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | 15 | int depth(TreeNode* root) { 16 | if(root == NULL) 17 | return INT_MAX; 18 | if(root->left == NULL && root->right == NULL) return 1; 19 | int x = depth(root->left); 20 | int y = depth(root->right); 21 | 22 | return min(x, y) + 1; 23 | } 24 | int minDepth(TreeNode* root) { 25 | if(root == NULL) 26 | return 0; 27 | return depth(root); 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Tree/112. Path Sum.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | bool hasPathSum(TreeNode* root, int targetSum) { 15 | if(!root) { 16 | return false; 17 | } 18 | if(!root->left && !root->right) { 19 | return targetSum == root->val; 20 | } 21 | bool leftPathSum = hasPathSum(root->left, targetSum - root->val); 22 | bool rightPathSum = hasPathSum(root->right, targetSum - root->val); 23 | 24 | return leftPathSum || rightPathSum; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Tree/144-Binary-Tree-Preorder-Traversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | 13 | // recursive solution 14 | class Solution { 15 | private: 16 | void dfs(TreeNode *node, vector &preorder){ 17 | if(node == NULL) return; 18 | 19 | preorder.push_back(node->val); 20 | dfs(node->left, preorder); 21 | dfs(node-> right, preorder); 22 | } 23 | public: 24 | vector preorderTraversal(TreeNode* root) { 25 | vectorpreorder; 26 | dfs(root, preorder); 27 | return preorder; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Tree/145-Binary-Tree-Postorder-Traversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | 13 | //recursive solution 14 | class Solution { 15 | private: 16 | void dfs(TreeNode *node, vector &postorder) { 17 | if(node == NULL) return; 18 | 19 | dfs(node->left, postorder); 20 | dfs(node->right, postorder); 21 | postorder.push_back(node->val); 22 | } 23 | public: 24 | vector postorderTraversal(TreeNode* root) { 25 | vectorpostorder; 26 | dfs(root, postorder); 27 | return postorder; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Tree/199-Binary-Tree-Right-Side-View.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | void dfs(TreeNode *node, int level, vector &ans) { 14 | 15 | if(node == NULL) return ; 16 | 17 | if(ans.size() == level) ans.push_back(node->val); 18 | dfs(node->right, level + 1, ans); 19 | dfs(node->left, level + 1, ans); 20 | } 21 | public: 22 | vector rightSideView(TreeNode* root) { 23 | vectorans; 24 | dfs(root, 0, ans); 25 | return ans; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Tree/222. Count Complete Tree Nodes.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | int countNodes(TreeNode* root) { 15 | if(root == NULL) { 16 | return 0; 17 | } 18 | int l = countNodes(root->left); 19 | int r = countNodes(root->right); 20 | 21 | int sum = l + r + 1; 22 | 23 | return sum; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Tree/226. Invert Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | void invertBinaryTree(TreeNode* root) { 15 | if(root == NULL) { 16 | return; 17 | } 18 | 19 | TreeNode* l = root->left; 20 | root->left = root->right; 21 | root->right = l; 22 | invertBinaryTree(root->left); 23 | invertBinaryTree(root->right); 24 | } 25 | 26 | TreeNode* invertTree(TreeNode* root) { 27 | TreeNode* ans = root; 28 | invertBinaryTree(root); 29 | return ans; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Tree/404. Sum of Left Leaves.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | int storeSum = 0; 14 | public: 15 | int sumOfLeftLeaves(TreeNode* root) { 16 | 17 | if(root != NULL) { 18 | if(root->left != NULL && root->left->left == NULL && root->left->right == NULL) { 19 | storeSum += root->left->val; 20 | } 21 | sumOfLeftLeaves(root->left); 22 | sumOfLeftLeaves(root->right); 23 | } 24 | return storeSum; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Tree/513. Find Bottom Left Tree Value.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | int findBottomLeftValue(TreeNode* root) { 15 | queueq; 16 | q.push(root); 17 | int leftMostValue; 18 | while(!q.empty()) { 19 | TreeNode* node = q.front(); 20 | q.pop(); 21 | 22 | leftMostValue = node->val; 23 | 24 | if(node->right) { 25 | q.push(node->right); 26 | } 27 | if(node->left) { 28 | q.push(node->left); 29 | } 30 | } 31 | return leftMostValue; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /Tree/543. Diameter of Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | int ans = 0; 15 | int dfs(TreeNode* root) { 16 | if(root == NULL) { 17 | return 0; 18 | } 19 | 20 | int leftdfs = dfs(root->left); 21 | int rightdfs = dfs(root->right); 22 | 23 | ans = max(ans, leftdfs + rightdfs); 24 | 25 | return 1 + max(leftdfs, rightdfs); 26 | } 27 | int diameterOfBinaryTree(TreeNode* root) { 28 | dfs(root); 29 | return ans; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Tree/700. Search in a Binary Search Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | TreeNode* searchBST(TreeNode* root, int val) { 15 | while(root != NULL && root->val != val) { 16 | if(root->val > val) 17 | root = root->left; 18 | else 19 | root = root->right; 20 | } 21 | return root; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Tree/938. Range Sum of BST.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | int rangeSumBST(TreeNode* root, int low, int high) { 15 | if(!root) { 16 | return 0; 17 | } 18 | 19 | int currentVal = (root->val >= low && root->val <= high) ? root->val : 0; 20 | 21 | int leftSum = rangeSumBST(root->left, low, high); 22 | int rightSum = rangeSumBST(root->right, low, high); 23 | 24 | return currentVal + leftSum + rightSum; 25 | 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Tree/94-Binary-Tree-Inorder-Traversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | 13 | // recursive approcah 14 | class Solution { 15 | 16 | private: 17 | void dfs(TreeNode *node, vector &inorder) { 18 | if(node == NULL) return; 19 | 20 | dfs(node -> left, inorder); 21 | inorder.push_back(node->val); 22 | dfs(node->right, inorder); 23 | } 24 | public: 25 | vector inorderTraversal(TreeNode* root) { 26 | vectorinorder; 27 | dfs(root, inorder); 28 | return inorder; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Tree/98. Validate Binary Search Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | 14 | void inOrder(TreeNode* root, vector &vec) { 15 | if(root == NULL) { 16 | return; 17 | } 18 | inOrder(root->left, vec); 19 | vec.push_back(root->val); 20 | inOrder(root->right, vec); 21 | } 22 | public: 23 | bool isValidBST(TreeNode* root) { 24 | vectorv; 25 | inOrder(root, v); 26 | for(int i = 1; i < v.size(); i++) { 27 | if(v[i] <= v[i - 1]) { 28 | return false; 29 | } 30 | } 31 | return true; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /Tree/Code : Count leaf nodes.cpp: -------------------------------------------------------------------------------- 1 | /************************************************************ 2 | 3 | Following is the structure for the TreeNode class 4 | 5 | template 6 | class TreeNode { 7 | public: 8 | T data; 9 | vector*> children; 10 | 11 | TreeNode(T data) { 12 | this->data = data; 13 | } 14 | 15 | ~TreeNode() { 16 | for (int i = 0; i < children.size(); i++) { 17 | delete children[i]; 18 | } 19 | } 20 | }; 21 | 22 | ************************************************************/ 23 | 24 | int getLeafNodeCount(TreeNode* root) { 25 | // Write your code here 26 | int count = 0; 27 | 28 | if(root->children.size() == 0) { 29 | count++; 30 | } 31 | 32 | for(int i = 0; i < root->children.size(); i++) { 33 | count += getLeafNodeCount(root->children[i]); 34 | } 35 | return count; 36 | } 37 | -------------------------------------------------------------------------------- /Tree/Code : Find a node.cpp: -------------------------------------------------------------------------------- 1 | /************************************************************ 2 | 3 | Following is the Binary Tree node structure 4 | 5 | template 6 | class BinaryTreeNode 7 | { 8 | public : 9 | T data; 10 | BinaryTreeNode *left; 11 | BinaryTreeNode *right; 12 | 13 | BinaryTreeNode(T data) 14 | { 15 | this -> data = data; 16 | left = NULL; 17 | right = NULL; 18 | } 19 | }; 20 | 21 | ************************************************************/ 22 | 23 | bool isNodePresent(BinaryTreeNode *root, int x) { 24 | // Write your code here 25 | if(root == NULL) { 26 | return false; 27 | } 28 | 29 | if(root->data == x) { 30 | return true; 31 | } 32 | 33 | bool leftPresent = isNodePresent(root->left, x); 34 | bool rightPresent = isNodePresent(root->right, x); 35 | 36 | return leftPresent || rightPresent; 37 | } 38 | -------------------------------------------------------------------------------- /Tree/Code : Find height.cpp: -------------------------------------------------------------------------------- 1 | /************************************************************ 2 | 3 | Following is the structure for the TreeNode class 4 | 5 | template 6 | class TreeNode { 7 | public: 8 | T data; 9 | vector*> children; 10 | 11 | TreeNode(T data) { 12 | this->data = data; 13 | } 14 | 15 | ~TreeNode() { 16 | for (int i = 0; i < children.size(); i++) { 17 | delete children[i]; 18 | } 19 | } 20 | }; 21 | 22 | ************************************************************/ 23 | 24 | int getHeight(TreeNode* root) { 25 | // Write your code here 26 | if(root == NULL) { 27 | return 0; 28 | } 29 | int ans = 0; 30 | for(int i = 0; i < root->children.size(); i++) { 31 | int childHeight = getHeight(root->children[i]); 32 | if(childHeight > ans) { 33 | ans = childHeight; 34 | } 35 | } 36 | return ans + 1; 37 | } 38 | -------------------------------------------------------------------------------- /Tree/Code : Find sum of nodes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | /************************************************************ 3 | 4 | Following is the structure for the TreeNode class 5 | 6 | template 7 | class TreeNode { 8 | public: 9 | T data; 10 | vector*> children; 11 | 12 | TreeNode(T data) { 13 | this->data = data; 14 | } 15 | 16 | ~TreeNode() { 17 | for (int i = 0; i < children.size(); i++) { 18 | delete children[i]; 19 | } 20 | } 21 | }; 22 | 23 | ************************************************************/ 24 | 25 | int sumOfNodes(TreeNode* root) { 26 | // Write your code here 27 | int sum = root->data; 28 | for(int i = 0; i < root->children.size(); i++) { 29 | sum += sumOfNodes(root->children[i]); 30 | } 31 | return sum; 32 | } 33 | -------------------------------------------------------------------------------- /Tree/Code : Height of Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /*********************************************************** 2 | Following is the Binary Tree Node class structure 3 | 4 | template 5 | class BinaryTreeNode { 6 | public : 7 | T data; 8 | BinaryTreeNode *left; 9 | BinaryTreeNode *right; 10 | 11 | BinaryTreeNode(T data) { 12 | this -> data = data; 13 | left = NULL; 14 | right = NULL; 15 | } 16 | }; 17 | 18 | ***********************************************************/ 19 | 20 | int height(BinaryTreeNode* root) { 21 | // Write our code here 22 | if(root == NULL) { 23 | return 0; 24 | } 25 | 26 | int leftHeight = height(root->left); 27 | int rightHeight = height(root->right); 28 | 29 | return 1 + max(leftHeight, rightHeight); 30 | } 31 | -------------------------------------------------------------------------------- /Tree/Code : Max data node.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | /************************************************************ 3 | 4 | Following is the structure for the TreeNode class 5 | 6 | template 7 | class TreeNode { 8 | public: 9 | T data; 10 | vector*> children; 11 | 12 | TreeNode(T data) { 13 | this->data = data; 14 | } 15 | 16 | ~TreeNode() { 17 | for (int i = 0; i < children.size(); i++) { 18 | delete children[i]; 19 | } 20 | } 21 | }; 22 | 23 | ************************************************************/ 24 | 25 | TreeNode* maxDataNode(TreeNode* root) { 26 | // Write your code here 27 | TreeNode*maximum = root; 28 | 29 | for(int i = 0; i < root->children.size(); i++) { 30 | TreeNode* maxData = maxDataNode(root->children[i]); 31 | if(maximum->data < maxData->data) 32 | maximum = maxData; 33 | } 34 | return maximum; 35 | } 36 | -------------------------------------------------------------------------------- /Tree/Code : Mirror.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************** 2 | Following is the Binary Tree Node class structure 3 | 4 | template 5 | class BinaryTreeNode { 6 | public : 7 | T data; 8 | BinaryTreeNode *left; 9 | BinaryTreeNode *right; 10 | 11 | BinaryTreeNode(T data) { 12 | this -> data = data; 13 | left = NULL; 14 | right = NULL; 15 | } 16 | }; 17 | 18 | ***********************************************************/ 19 | 20 | void mirrorBinaryTree(BinaryTreeNode* root) { 21 | // Write your code here 22 | if(root == NULL || (root->left == NULL && root->right == NULL)) { 23 | return; 24 | } 25 | 26 | swap(root->left, root->right); 27 | 28 | mirrorBinaryTree(root->left); 29 | mirrorBinaryTree(root->right); 30 | } 31 | -------------------------------------------------------------------------------- /Tree/Code : PostOrder Traversal.cpp: -------------------------------------------------------------------------------- 1 | /************************************************************ 2 | 3 | Following is the structure for the TreeNode class 4 | 5 | template 6 | class TreeNode { 7 | public: 8 | T data; 9 | vector*> children; 10 | 11 | TreeNode(T data) { 12 | this->data = data; 13 | } 14 | 15 | ~TreeNode() { 16 | for (int i = 0; i < children.size(); i++) { 17 | delete children[i]; 18 | } 19 | } 20 | }; 21 | 22 | ************************************************************/ 23 | 24 | void printPostOrder(TreeNode* root) { 25 | // Write your code here 26 | if(root == NULL) { 27 | return; 28 | } 29 | for(int i = 0; i < root->children.size(); i++) { 30 | printPostOrder(root->children[i]); 31 | } 32 | cout << root->data << " "; 33 | } 34 | -------------------------------------------------------------------------------- /Tree/Code: Search in BST.cpp: -------------------------------------------------------------------------------- 1 | /********************************************************** 2 | 3 | Following is the Binary Tree Node class structure 4 | 5 | template 6 | class BinaryTreeNode { 7 | public : 8 | T data; 9 | BinaryTreeNode *left; 10 | BinaryTreeNode *right; 11 | 12 | BinaryTreeNode(T data) { 13 | this -> data = data; 14 | left = NULL; 15 | right = NULL; 16 | } 17 | }; 18 | 19 | ***********************************************************/ 20 | 21 | bool searchInBST(BinaryTreeNode *root , int k) { 22 | // Write your code here 23 | if(root == NULL) { 24 | return false; 25 | } 26 | 27 | if(root->data == k) { 28 | return true; 29 | } 30 | 31 | if(k < root->data) { 32 | return searchInBST(root->left, k); 33 | } 34 | 35 | return searchInBST(root->right, k); 36 | } 37 | -------------------------------------------------------------------------------- /Tree/Contains x.cpp: -------------------------------------------------------------------------------- 1 | /************************************************************ 2 | 3 | Following is the structure for the TreeNode class 4 | 5 | template 6 | class TreeNode { 7 | public: 8 | T data; 9 | vector*> children; 10 | 11 | TreeNode(T data) { 12 | this->data = data; 13 | } 14 | 15 | ~TreeNode() { 16 | for (int i = 0; i < children.size(); i++) { 17 | delete children[i]; 18 | } 19 | } 20 | }; 21 | 22 | ************************************************************/ 23 | 24 | bool isPresent(TreeNode* root, int x) { 25 | // Write your code here 26 | if(root == NULL) { 27 | return false; 28 | } 29 | if(root->data == x) { 30 | return true; 31 | } 32 | for(int i = 0; i < root->children.size(); i++) { 33 | if(isPresent(root->children[i] , x)) 34 | return true; 35 | } 36 | return false; 37 | } 38 | -------------------------------------------------------------------------------- /Tree/Count nodes.cpp: -------------------------------------------------------------------------------- 1 | /************************************************************ 2 | 3 | Following is the structure for the TreeNode class 4 | 5 | template 6 | class TreeNode { 7 | public: 8 | T data; 9 | vector*> children; 10 | 11 | TreeNode(T data) { 12 | this->data = data; 13 | } 14 | 15 | ~TreeNode() { 16 | for (int i = 0; i < children.size(); i++) { 17 | delete children[i]; 18 | } 19 | } 20 | }; 21 | 22 | ************************************************************/ 23 | 24 | int getLargeNodeCount(TreeNode* root, int x) { 25 | // Write your code here 26 | int count = 0; 27 | 28 | if(root->data > x) { 29 | count++; 30 | } 31 | 32 | for(int i = 0; i < root->children.size(); i++) { 33 | count += getLargeNodeCount(root->children[i], x); 34 | } 35 | return count; 36 | } 37 | -------------------------------------------------------------------------------- /Two Pointer/1512. Number of Good Pairs.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numIdenticalPairs(vector& nums) { 4 | int n = nums.size(); 5 | int count = 0; 6 | for(int i = 0; i < n - 1; i++) { 7 | for(int j = i; j < n; j++) { 8 | if(nums[i] == nums[j] && i < j) 9 | count++; 10 | } 11 | } 12 | return count; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Two Pointer/1658. Minimum Operations to Reduce X to Zero.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minOperations(vector& nums, int x) { 4 | int target = 0, n = nums.size(); 5 | for (int num : nums) target += num; 6 | target -= x; 7 | 8 | if (target == 0) return n; 9 | 10 | int max_len = 0, cur_sum = 0, left = 0; 11 | 12 | for (int right = 0; right < n; ++right) { 13 | cur_sum += nums[right]; 14 | while (left <= right && cur_sum > target) { 15 | cur_sum -= nums[left]; 16 | left++; 17 | } 18 | if (cur_sum == target) { 19 | max_len = max(max_len, right - left + 1); 20 | } 21 | } 22 | 23 | return max_len ? n - max_len : -1; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Two Pointer/42. Trapping Rain Water.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int trap(vector& height) { 4 | int i = 0, left_max = height[0], sum = 0; 5 | int j = height.size() - 1, right_max = height[j]; 6 | while(i < j) { 7 | if(left_max <= right_max) { 8 | sum += (left_max - height[i]); 9 | i++; 10 | left_max = max(left_max, height[i]); 11 | }else { 12 | sum += (right_max - height[j]); 13 | j--; 14 | right_max = max(right_max, height[j]); 15 | } 16 | } 17 | return sum; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Two Pointer/844. Backspace String Compare.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool backspaceCompare(string s, string t) { 4 | int k = processString(s); 5 | int p = processString(t); 6 | 7 | if(k != p) return false; 8 | 9 | for(int i = 0; i < k; i++) { 10 | if(s[i] != t[i]) return false; 11 | } 12 | return true; 13 | } 14 | private: 15 | int processString(string &str) { 16 | int k = 0; 17 | for(char c : str) { 18 | if(c != '#') { 19 | str[k++] = c; 20 | } else if (k > 0) { 21 | k--; 22 | } 23 | } 24 | return k; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Two Pointer/948. Bag of Tokens.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int bagOfTokensScore(vector& tokens, int power) { 4 | sort(tokens.begin(), tokens.end()); 5 | int n = tokens.size(); 6 | int score = 0; 7 | int max_score = 0; 8 | int left = 0; 9 | int right = n - 1; 10 | 11 | while (left <= right) { 12 | if (power >= tokens[left]) { 13 | power -= tokens[left]; 14 | score += 1; 15 | left += 1; 16 | max_score = max(max_score, score); 17 | } else if (score > 0) { 18 | power += tokens[right]; 19 | score -= 1; 20 | right -= 1; 21 | } else { 22 | break; 23 | } 24 | } 25 | 26 | return max_score; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Two Pointer/977. Squares of a Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector sortedSquares(vector& nums) { 4 | int n = nums.size(); 5 | int low = 0, high = nums.size() - 1; 6 | vectorans(nums.size()); 7 | for(int i = n - 1; i >= 0; i--) { 8 | if(abs(nums[low]) > abs(nums[high])) { 9 | ans[i] = nums[low] * nums[low]; 10 | low++; 11 | }else { 12 | ans[i] = nums[high] * nums[high]; 13 | high--; 14 | } 15 | } 16 | return ans; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /mathematics/1-Absolute-Value.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | // User function Template for C++ 7 | 8 | class Solution{ 9 | public: 10 | int absolute(int I) { 11 | // Your code goes here 12 | return abs(I); 13 | } 14 | 15 | }; 16 | 17 | // { Driver Code Starts. 18 | 19 | int main() { 20 | int T; // number of testcases 21 | cin >> T; // input number of testcases 22 | while (T--) { 23 | int I; 24 | cin >> I; 25 | Solution ob; 26 | cout << ob.absolute(I) << endl; // print the output 27 | } 28 | return 0; 29 | } // } Driver Code Ends 30 | -------------------------------------------------------------------------------- /mathematics/1291. Sequential Digits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector sequentialDigits(int low, int high) { 4 | vector a; 5 | 6 | for (int i = 1; i <= 9; ++i) { 7 | int num = i; 8 | int nextDigit = i + 1; 9 | 10 | while (num <= high && nextDigit <= 9) { 11 | num = num * 10 + nextDigit; 12 | if (low <= num && num <= high) a.push_back(num); 13 | ++nextDigit; 14 | } 15 | } 16 | 17 | sort(a.begin(), a.end()); 18 | return a; 19 | } 20 | }; 21 | 22 | 23 | -------------------------------------------------------------------------------- /mathematics/1342. Number of Steps to Reduce a Number to Zero.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numberOfSteps(int num) { 4 | if(num <= 1) return num; 5 | int counter = 0; 6 | while(num > 0) { 7 | if(num % 2 == 0) { 8 | num /= 2; 9 | } else { 10 | num -= 1; 11 | } 12 | counter++; 13 | } 14 | return counter; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /mathematics/172-Factorial-Trailing-Zeroes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int trailingZeroes(int n) { 4 | int res = 0; 5 | for(int i = 5; i <= n; i = i * 5) { 6 | res = res + (n/i); 7 | } 8 | return res; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /mathematics/204-Count-Primes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countPrimes(int n) { 4 | int count = 0; 5 | int arr[n + 1]; 6 | if(n > 2) { 7 | count++; 8 | for(int i = 3; i < n; i+=2) { 9 | arr[i] = 0; 10 | } 11 | for(int j = 3; j < n; j+=2) { 12 | if(arr[j] == 0) { 13 | count++; 14 | for(int i = 2*j; i < n; i+=j) { 15 | arr[i] = 1; 16 | } 17 | } 18 | } 19 | } 20 | return count; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /mathematics/231. Power of Two.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPowerOfTwo(int n) { 4 | if(n <= 0) 5 | return false; 6 | while(n % 2 == 0) { 7 | n /= 2; 8 | } 9 | return n == 1; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /mathematics/2485. Find the Pivot Integer.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int pivotInteger(int n) { 4 | double x = sqrt(n * (n + 1) / 2.0); 5 | 6 | if(fmod(x, 1.0) != 0) { 7 | return -1; 8 | } else { 9 | return static_cast(x); 10 | } 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /mathematics/279. Perfect Squares.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int solve(int n) { 4 | if(n == 0) return 0; 5 | 6 | int result = n; 7 | for(int i = 1; i <= sqrt(n); i++) { 8 | result = min(result, 1 + solve(n - i * i)); 9 | } 10 | 11 | return result; 12 | } 13 | int numSquares(int n) { 14 | return solve(n); 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /mathematics/326. Power of Three.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPowerOfThree(int n) { 4 | if (n <= 0) 5 | return false; 6 | while(n % 3 == 0) { 7 | n /= 3; 8 | } 9 | return n == 1; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /mathematics/342. Power of Four.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPowerOfFour(int n) { 4 | if(n <= 0) 5 | return false; 6 | double logResult = log(n) / log(4); 7 | return logResult == int(logResult); 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /mathematics/343. Integer Break.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int integerBreak(int n) { 4 | if (n <= 3) return n - 1; 5 | int quotient = n / 3, remainder = n % 3; 6 | if (remainder == 0) return pow(3, quotient); 7 | if (remainder == 1) return pow(3, quotient - 1) * 4; 8 | return pow(3, quotient) * 2; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /mathematics/50-Pow(x, n).cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double myPow(double x, int n) { 4 | double ans = pow(x,n); 5 | return ans; 6 | } 7 | }; 8 | -------------------------------------------------------------------------------- /mathematics/7. Reverse Integer: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int reverse(int x) { 4 | long int num = 0; 5 | if(x >= 2147483647 || x <= -2147483647) 6 | return 0; 7 | if(x>0){ 8 | while(x>0){ 9 | num = num * 10; 10 | if(num >= 2147483647 || num <= -2147483647) 11 | return 0; 12 | num = num + (x%10); 13 | x = x/10; 14 | 15 | } 16 | } 17 | else { 18 | x = -1 * x; 19 | while(x>0){ 20 | num = num * 10; 21 | if(num >= 2147483647 || num <= -2147483647) 22 | return 0; 23 | num = num + (x%10); 24 | x = x/10; 25 | 26 | } 27 | num = -1 * num; 28 | } 29 | return int(num); 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /mathematics/70. Climbing Stairs.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | int climb(int current, int n) { 5 | if(current > n) { 6 | return 0; 7 | } 8 | 9 | if(current == n) { 10 | return 1; 11 | } 12 | 13 | return climb(current + 1, n) + climb(current + 2, n); 14 | } 15 | int climbStairs(int n) { 16 | return climb(0, n); 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /mathematics/9-Palindrome-Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPalindrome(int x) { 4 | if(x < 0) 5 | return false; 6 | 7 | long int res = 0; 8 | int temp = x; 9 | while(temp != 0) { 10 | int lastDigit = temp % 10; 11 | res = res * 10 + lastDigit; 12 | temp = temp/10; 13 | } 14 | if(res == x) 15 | return true; 16 | else 17 | return false; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /mathematics/Addition Under Modulo.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | //Initial Template for C++ 3 | 4 | #include 5 | using namespace std; 6 | 7 | // } Driver Code Ends 8 | //User function Template for C++ 9 | 10 | class Solution{ 11 | public: 12 | long long sumUnderModulo(long long a,long long b) 13 | { 14 | // code here 15 | long long modResult = (pow(10, 9) + 7); 16 | long long ans = ((a % modResult) + (b % modResult)) % modResult; 17 | return ans; 18 | } 19 | }; 20 | 21 | //{ Driver Code Starts. 22 | int main() { 23 | int T; 24 | cin>>T; 25 | while(T--) 26 | { 27 | long long a; 28 | long long b; 29 | cin>>a>>b; 30 | Solution ob; 31 | cout< 5 | using namespace std; 6 | 7 | 8 | // } Driver Code Ends 9 | //User function Template for C++ 10 | 11 | class Solution{ 12 | public: 13 | 14 | //You need to complete this function 15 | double cToF(int C) 16 | { 17 | //Your code here 18 | return (C * 1.8) + 32; 19 | } 20 | }; 21 | 22 | //{ Driver Code Starts. 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | int main() 31 | { 32 | int T;//number of testcases 33 | int C,F; 34 | cin >> T; //input number of testcases 35 | while(T--){ 36 | cin >> C;//input temperature in celscius 37 | Solution ob; 38 | cout << floor(ob.cToF(C)) << endl; //print the output 39 | } 40 | return 0; 41 | } 42 | // } Driver Code Ends 43 | -------------------------------------------------------------------------------- /mathematics/Count-Odd-Factors.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | class Solution{ 7 | public: 8 | int count(int N){ 9 | // code here 10 | return sqrt(N); 11 | } 12 | }; 13 | 14 | // { Driver Code Starts. 15 | int main() 16 | { 17 | int t; 18 | cin>>t; 19 | while(t--) 20 | { 21 | int N; 22 | cin>>N; 23 | Solution ob; 24 | cout << ob.count(N) << endl; 25 | } 26 | return 0; 27 | } // } Driver Code Ends 28 | -------------------------------------------------------------------------------- /mathematics/Digits In Factorial.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | //Initial Template for C++ 3 | 4 | 5 | #include 6 | using namespace std; 7 | 8 | // } Driver Code Ends 9 | //User function Template for C++ 10 | 11 | class Solution{ 12 | public: 13 | int digitsInFactorial(int N) 14 | { 15 | // code here 16 | if(N < 0) return 0; 17 | if(N <= 1) return 1; 18 | double res = 0; 19 | for(int i = 2; i <= N; i++) { 20 | res += log10(i); 21 | } 22 | return floor(res) + 1; 23 | } 24 | }; 25 | 26 | //{ Driver Code Starts. 27 | 28 | int main() 29 | { 30 | int T; 31 | 32 | //taking testcases 33 | cin>>T; 34 | while(T--) 35 | { 36 | int N; 37 | 38 | //taking N 39 | cin>>N; 40 | Solution ob; 41 | //calling method digitsInFactorial() 42 | cout< 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | class Solution{ 7 | public: 8 | long long int factorial(int N){ 9 | //code here 10 | long long int res = 1; 11 | for(int i = 2; i <= N; i++) { 12 | res = res * i; 13 | } 14 | return res; 15 | } 16 | }; 17 | 18 | // { Driver Code Starts. 19 | int main() 20 | { 21 | int t; 22 | cin>>t; 23 | while(t--) 24 | { 25 | int N; 26 | cin>>N; 27 | Solution ob; 28 | cout << ob.factorial(N) << endl; 29 | } 30 | return 0; 31 | } // } Driver Code Ends 32 | -------------------------------------------------------------------------------- /mathematics/Find the median.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | class Solution 7 | { 8 | public: 9 | public: 10 | int find_median(vector v) 11 | { 12 | // Code here. 13 | int n = v.size(); 14 | sort(v.begin(), v.end()); 15 | if(n % 2 != 0) { 16 | return v[floor(n/2)]; 17 | } 18 | else{ 19 | return floor((v[floor(n/2)]+v[floor(n/2)-1])/2); 20 | } 21 | } 22 | }; 23 | 24 | //{ Driver Code Starts. 25 | int main(){ 26 | int T; 27 | cin >> T; 28 | while(T--) 29 | { 30 | int n; 31 | cin >> n; 32 | vector v(n); 33 | for(int i = 0; i < n; i++) 34 | cin>>v[i]; 35 | Solution ob; 36 | int ans = ob.find_median(v); 37 | cout << ans <<"\n"; 38 | } 39 | return 0; 40 | } 41 | 42 | // } Driver Code Ends 43 | -------------------------------------------------------------------------------- /mathematics/GCD-of-two-numbers.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | //User function Template for C++ 7 | class Solution 8 | { 9 | public: 10 | int gcd(int A, int B) 11 | { 12 | // code here 13 | if(B == 0) 14 | return A; 15 | else 16 | return gcd(B, A % B); 17 | } 18 | }; 19 | 20 | // { Driver Code Starts. 21 | 22 | int main() 23 | { 24 | int t; 25 | cin >> t; 26 | while (t--) 27 | { 28 | int A, B; 29 | cin >> A >> B; 30 | Solution ob; 31 | cout << ob.gcd(A, B) << "\n"; 32 | } 33 | return 0; 34 | } // } Driver Code Ends 35 | -------------------------------------------------------------------------------- /mathematics/GP Term.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | //Initial Template for C++ 3 | 4 | #include 5 | using namespace std; 6 | 7 | 8 | // } Driver Code Ends 9 | //User function Template for C++ 10 | 11 | class Solution{ 12 | public: 13 | //Complete this function 14 | double termOfGP(int A,int B,int N) 15 | { 16 | //Your code here 17 | double ratio = (double)B/A; 18 | return (double) A*pow(ratio, N - 1); 19 | } 20 | }; 21 | 22 | //{ Driver Code Starts. 23 | 24 | 25 | int main() 26 | { 27 | int T; //testcases total 28 | cin>>T;//input the testcases 29 | 30 | for(int i=0;i>A>>B; //input first and second term of gp 34 | int N; 35 | cin>>N; //input n 36 | Solution ob; 37 | cout< 5 | using namespace std; 6 | 7 | // } Driver Code Ends 8 | //User function Template for C++ 9 | 10 | class Solution{ 11 | public: 12 | 13 | int solve(int n) { 14 | if(n == 0) return 0; 15 | 16 | int result = n; 17 | for(int i = 1; i * i <= n; i++) { 18 | result = min(result, 1 + solve(n - i * i)); 19 | } 20 | return result; 21 | } 22 | int MinSquares(int n) 23 | { 24 | // Code here 25 | return solve(n); 26 | } 27 | }; 28 | 29 | //{ Driver Code Starts. 30 | int main(){ 31 | int tc; 32 | cin >> tc; 33 | while(tc--){ 34 | int n; 35 | cin >> n; 36 | Solution ob; 37 | int ans = ob.MinSquares(n); 38 | cout << ans <<"\n"; 39 | } 40 | return 0; 41 | } 42 | // } Driver Code Ends 43 | -------------------------------------------------------------------------------- /mathematics/Multiplication Under Modulo.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | //Initial Template for C++ 3 | 4 | #include 5 | using namespace std; 6 | 7 | // } Driver Code Ends 8 | //User function Template for C++ 9 | 10 | class Solution{ 11 | public: 12 | int multiplicationUnderModulo(long long a,long long b) 13 | { 14 | //your code here 15 | long long modResult = (pow(10, 9) + 7); 16 | return ((a % modResult) * (b % modResult)) % modResult; 17 | } 18 | }; 19 | 20 | //{ Driver Code Starts. 21 | int main() { 22 | int T; 23 | 24 | //taking testcases 25 | cin>>T; 26 | while(T--) 27 | { 28 | long long a; 29 | long long b; 30 | 31 | //taking input a and b 32 | cin>>a>>b; 33 | Solution ob; 34 | //calling multiplicationUnderModulo() function 35 | cout< 5 | using namespace std; 6 | 7 | // } Driver Code Ends 8 | 9 | 10 | class Solution{ 11 | public: 12 | int find(int n){ 13 | // Code here 14 | float ans = (sqrt(1+8*n)-1)/2; 15 | if(ans == (int) ans) 16 | return ans; 17 | return -1; 18 | } 19 | }; 20 | 21 | // { Driver Code Starts. 22 | int main(){ 23 | int tc; 24 | cin >> tc; 25 | while(tc--){ 26 | int n; 27 | cin >> n; 28 | Solution ob; 29 | int ans = ob.find(n); 30 | cout << ans <<"\n"; 31 | } 32 | return 0; 33 | } // } Driver Code Ends 34 | -------------------------------------------------------------------------------- /mathematics/Number-of-divisors.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | //Initial Template for C++ 3 | 4 | 5 | #include 6 | using namespace std; 7 | 8 | // } Driver Code Ends 9 | //User function Template for C++ 10 | 11 | class Solution 12 | { 13 | public: 14 | int count_divisors(int n) 15 | { 16 | //Code here. 17 | if(n % 3 != 0) return 0; 18 | int count = 1; 19 | for(int i = 3; i <= n/2; i+=3) { 20 | if(n % i == 0) { 21 | count++; 22 | } 23 | } 24 | return count; 25 | } 26 | }; 27 | 28 | //{ Driver Code Starts. 29 | int main(){ 30 | int T; 31 | cin >> T; 32 | while(T--) 33 | { 34 | int n; 35 | cin >> n; 36 | Solution ob; 37 | int ans = ob.count_divisors(n); 38 | cout << ans << "\n"; 39 | } 40 | return 0; 41 | } 42 | // } Driver Code Ends 43 | -------------------------------------------------------------------------------- /mathematics/Odd-or-Even.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | class Solution{ 7 | public: 8 | string oddEven(int N){ 9 | // code here 10 | for(int i = 0; i < N; i++) { 11 | if(N % 2 == 0){ 12 | return "even"; 13 | }else { 14 | return "odd"; 15 | } 16 | } 17 | } 18 | }; 19 | 20 | // { Driver Code Starts. 21 | int main() 22 | { 23 | int t; 24 | cin>>t; 25 | while(t--) 26 | { 27 | int N; 28 | cin >> N; 29 | Solution ob; 30 | cout << ob.oddEven(N) << endl; 31 | } 32 | return 0; 33 | } // } Driver Code Ends 34 | -------------------------------------------------------------------------------- /mathematics/Palindrome.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | //Initial Template for C++ 3 | 4 | 5 | #include 6 | using namespace std; 7 | 8 | // } Driver Code Ends 9 | //User function Template for C++ 10 | 11 | class Solution 12 | { 13 | public: 14 | string is_palindrome(int n) 15 | { 16 | // Code here. 17 | int res = 0; 18 | int temp = n; 19 | while(temp != 0) { 20 | int lastDigit = temp % 10; 21 | res = res * 10 + lastDigit; 22 | temp = temp / 10; 23 | } 24 | if(res == n) 25 | return "Yes"; 26 | else 27 | return "No"; 28 | } 29 | }; 30 | 31 | // { Driver Code Starts. 32 | int main(){ 33 | int T; 34 | cin >> T; 35 | while(T--) 36 | { 37 | int n; 38 | cin >> n; 39 | Solution ob; 40 | string ans = ob.is_palindrome(n); 41 | cout << ans <<"\n"; 42 | } 43 | return 0; 44 | } 45 | // } Driver Code Ends 46 | -------------------------------------------------------------------------------- /mathematics/Primality Test.cpp: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | //Initial Template for C++ 3 | 4 | #include 5 | using namespace std; 6 | 7 | 8 | // } Driver Code Ends 9 | //User function Template for C++ 10 | 11 | class Solution{ 12 | public: 13 | bool isPrime(int N) 14 | { 15 | //Your code here 16 | for(int i = 2; i <= sqrt(N); i++) { 17 | if(N % i == 0) 18 | return false; 19 | } 20 | return true; 21 | } 22 | 23 | }; 24 | 25 | //{ Driver Code Starts. 26 | 27 | int main() 28 | { 29 | int T; //testcases 30 | cin>>T; //input testcases 31 | while(T--) //while testcase have not been exhausted 32 | { 33 | int N; 34 | cin>>N; //input n 35 | Solution ob; 36 | if(ob.isPrime(N)) 37 | cout<<"Yes"; 38 | else 39 | cout<<"No"; 40 | 41 | cout << endl; 42 | } 43 | return 0; 44 | } 45 | 46 | // } Driver Code Ends 47 | -------------------------------------------------------------------------------- /mathematics/Prime-Number.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | class Solution{ 7 | public: 8 | int isPrime(int N){ 9 | // code here 10 | if (N == 1) 11 | return 0; 12 | if(N == 2 || N == 3) return 1; 13 | if(N % 2 == 0 || N % 3 == 0) return 0; 14 | for(int i = 5; i*i <= N; i=i+6) { 15 | if(N % i == 0 || N % (i + 2) == 0) 16 | return 0; 17 | } 18 | return 1; 19 | } 20 | }; 21 | 22 | 23 | // { Driver Code Starts. 24 | int main() 25 | { 26 | int t; 27 | cin>>t; 28 | while(t--) 29 | { 30 | int N; 31 | cin>>N; 32 | Solution ob; 33 | cout << ob.isPrime(N) << endl; 34 | } 35 | return 0; 36 | } // } Driver Code Ends 37 | -------------------------------------------------------------------------------- /mathematics/Sum-Of-Digits.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | class Solution{ 7 | public: 8 | int sumOfDigits(int N){ 9 | //code here 10 | int res = 0; 11 | int temp = N; 12 | while(temp != 0) { 13 | int lastDigit = temp % 10; 14 | res = res + lastDigit; 15 | temp = temp / 10; 16 | } 17 | return res; 18 | } 19 | }; 20 | 21 | // { Driver Code Starts. 22 | int main() 23 | { 24 | int t; 25 | cin>>t; 26 | while(t--) 27 | { 28 | int N; 29 | cin>>N; 30 | Solution ob; 31 | cout << ob.sumOfDigits(N) << endl; 32 | } 33 | return 0; 34 | } // } Driver Code Ends 35 | -------------------------------------------------------------------------------- /mathematics/Sum-of-fifth-powers-of-the-first-n-natural-numbers.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | // Initial template for C++ 3 | 4 | #include 5 | using namespace std; 6 | 7 | // } Driver Code Ends 8 | // User function template for C++ 9 | 10 | class Solution { 11 | public: 12 | long long sumOfFifthPowers(long long N) { 13 | // code here 14 | long long i, sum = 0; 15 | for(i = 1; i <= N; i++) { 16 | sum = sum + i * i * i * i * i; 17 | } 18 | return sum; 19 | } 20 | }; 21 | 22 | // { Driver Code Starts. 23 | int main() { 24 | int t; 25 | cin >> t; 26 | while (t--) { 27 | int N; 28 | cin >> N; 29 | Solution ob; 30 | cout << ob.sumOfFifthPowers(N) << "\n"; 31 | } 32 | } // } Driver Code Ends 33 | -------------------------------------------------------------------------------- /mathematics/Sum-of-first-n-terms.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | // Initial template for C++ 3 | #include 4 | using namespace std; 5 | 6 | // } Driver Code Ends 7 | // User function template for C++ 8 | 9 | class Solution { 10 | public: 11 | long long sumOfSeries(long long N) { 12 | // code here 13 | long long sum = N * (N + 1)/2; 14 | return sum * sum; 15 | } 16 | }; 17 | 18 | // { Driver Code Starts. 19 | int main() { 20 | int t; 21 | cin >> t; 22 | while (t--) { 23 | long long N; 24 | cin >> N; 25 | Solution ob; 26 | cout << ob.sumOfSeries(N) << "\n"; 27 | } 28 | } // } Driver Code Ends 29 | -------------------------------------------------------------------------------- /mathematics/Trailing-zeroes-in-factorial.cpp: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | #include 3 | using namespace std; 4 | 5 | // } Driver Code Ends 6 | //User function Template for C++ 7 | class Solution 8 | { 9 | public: 10 | int trailingZeroes(int N) 11 | { 12 | // Write Your Code here 13 | int res = 0; 14 | for(int i = 5; i <= N; i = i * 5) { 15 | res = (res + (N/i)); 16 | } 17 | return res; 18 | } 19 | }; 20 | 21 | // { Driver Code Starts. 22 | int main() 23 | { 24 | int t; 25 | cin >> t; 26 | while (t--) 27 | { 28 | int N; 29 | cin >> N; 30 | Solution ob; 31 | int ans = ob.trailingZeroes(N); 32 | cout<>& mat) { 4 | int special = 0; 5 | 6 | for (const auto& row : mat) { 7 | if (accumulate(row.begin(), row.end(), 0) == 1) { 8 | int colIdx = distance(row.begin(), find(row.begin(), row.end(), 1)); 9 | special += getColumnSum(mat, colIdx) == 1; 10 | } 11 | } 12 | 13 | return special; 14 | } 15 | 16 | private: 17 | int getColumnSum(const vector>& mat, int colIdx) { 18 | int sum = 0; 19 | for (const auto& row : mat) { 20 | sum += row[colIdx]; 21 | } 22 | return sum; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /matrix/2482. Difference Between Ones and Zeros in Row and Column.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> onesMinusZeros(vector>& grid) { 4 | int m = grid.size(); 5 | int n = grid[0].size(); 6 | 7 | vector rowOnes(m, 0); 8 | vector colOnes(n, 0); 9 | 10 | // Count ones in each row and column 11 | for (int i = 0; i < m; ++i) { 12 | for (int j = 0; j < n; ++j) { 13 | rowOnes[i] += grid[i][j]; 14 | colOnes[j] += grid[i][j]; 15 | } 16 | } 17 | 18 | // Calculate the difference matrix 19 | for (int i = 0; i < m; ++i) { 20 | for (int j = 0; j < n; ++j) { 21 | grid[i][j] = 2 * (rowOnes[i] + colOnes[j]) - m - n; 22 | } 23 | } 24 | 25 | return grid; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /matrix/463. Island Perimeter.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int islandPerimeter(vector>& grid) { 4 | int perimeter = 0; 5 | int rows = grid.size(); 6 | int cols = grid[0].size(); 7 | 8 | for (int r = 0; r < rows; r++) { 9 | for (int c = 0; c < cols; c++) { 10 | if (grid[r][c] == 1) { 11 | perimeter += 4; 12 | if (r > 0 && grid[r-1][c] == 1) { 13 | perimeter -= 2; 14 | } 15 | if (c > 0 && grid[r][c-1] == 1) { 16 | perimeter -= 2; 17 | } 18 | } 19 | } 20 | } 21 | 22 | return perimeter; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /matrix/661. Image Smoother.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> imageSmoother(vector>& img) { 4 | int rows = img.size(); 5 | int cols = img[0].size(); 6 | std::vector> result(rows, std::vector(cols, 0)); 7 | 8 | for (int i = 0; i < rows; ++i) { 9 | for (int j = 0; j < cols; ++j) { 10 | int total_sum = 0; 11 | int count = 0; 12 | 13 | for (int x = std::max(0, i-1); x < std::min(rows, i+2); ++x) { 14 | for (int y = std::max(0, j-1); y < std::min(cols, j+2); ++y) { 15 | total_sum += img[x][y]; 16 | count += 1; 17 | } 18 | } 19 | 20 | result[i][j] = total_sum / count; 21 | } 22 | } 23 | 24 | return result; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /matrix/867. Transpose Matrix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> transpose(vector>& matrix) { 4 | int num_rows = matrix.size(); 5 | int num_cols = matrix[0].size(); 6 | 7 | vector>ans; 8 | 9 | for (int j = 0; j < num_cols; j++) { 10 | 11 | vectortemp; 12 | 13 | for (int i = 0; i < num_rows; i++) { 14 | 15 | temp.push_back(matrix[i][j]); 16 | 17 | } 18 | 19 | ans.push_back(temp); 20 | 21 | } 22 | 23 | return ans; 24 | } 25 | }; 26 | --------------------------------------------------------------------------------