├── CSES ├── Introductory Problems │ ├── Apple Division 1623.cpp │ ├── Bit Strings 1617.cpp │ ├── Chessboard and Queens 1624.cpp │ ├── Coin Piles 1754.cpp │ ├── Creating Strings 1622.cpp │ ├── Digit Queries 2431.cpp │ ├── Gray Code 2205.cpp │ ├── Grid Paths 1625.cpp │ ├── Increasing Array 1094.cpp │ ├── Missing Number 1083.cpp │ ├── Number Spiral 1071.cpp │ ├── Palindrome Reorder 1755.cpp │ ├── Permutations 1070.cpp │ ├── Repetitions 1069.cpp │ ├── Tower of Hanoi 2165.cpp │ ├── Trailing Zeros 1618.cpp │ ├── Two Knights 1072.cpp │ ├── Two Sets 1092.cpp │ └── Weird Algorithm 1068.cpp ├── RangeQueries │ ├── 1190 Subarray Sum Queries.cpp │ ├── 2166 Prefix Sum Queries.cpp │ └── 2206 Pizzeria Queries.cpp ├── Tree │ ├── 1130.cpp │ ├── 1131.cpp │ ├── 1139.cpp │ ├── 1674.cpp │ └── readme.md └── readme.md ├── Contests └── Credit Suisse Global Coding Challenge 2021 │ ├── Question1.c │ ├── Question2.c │ ├── Question3.c │ ├── Question4.c │ ├── Question5.c │ ├── Question6.cpp │ ├── Question7.c │ ├── Question8 O(N*K).c │ ├── Question9.c │ └── readme.md ├── Dynamic Programming ├── Atcoder Educational DP Contest │ ├── dp_a.cpp │ ├── dp_b.cpp │ ├── dp_c.cpp │ ├── dp_d.cpp │ ├── dp_e.cpp │ ├── dp_f.cpp │ ├── dp_g.cpp │ ├── dp_h.cpp │ ├── dp_i.cpp │ ├── dp_j.cpp │ ├── dp_k.cpp │ ├── dp_l.cpp │ ├── dp_m.cpp │ ├── dp_n.cpp │ ├── dp_o.cpp │ ├── dp_p.cpp │ ├── dp_q.cpp │ ├── dp_r.cpp │ ├── dp_s.cpp │ ├── dp_t.cpp │ ├── dp_u.cpp │ ├── dp_v.cpp │ ├── dp_z.cpp │ └── readme.txt ├── CSES │ ├── 1093.cpp │ ├── 1097.cpp │ ├── 1140.cpp │ ├── 1145.cpp │ ├── 1158.cpp │ ├── 1633.cpp │ ├── 1634.cpp │ ├── 1635.cpp │ ├── 1636.cpp │ ├── 1637.cpp │ ├── 1638.cpp │ ├── 1639.cpp │ ├── 1653.cpp │ ├── 1744.cpp │ ├── 1745.cpp │ ├── 1746.cpp │ ├── 2220.cpp │ └── readme.txt ├── Digit DP │ ├── CSES Counting Numbers.cpp │ ├── CodeChef ENCODING.cpp │ ├── countNumbersWithParityOfDigits.cpp │ ├── countOfNumbersWithDigitSum.cpp │ ├── digitSumAndNumberDivisibleByK.cpp │ └── sumOfDigitSum.cpp ├── LeetCode │ ├── 01 Matrix.cpp │ ├── 2 Keys Keyboard.cpp │ ├── Airplane Seat Assignment Probability.cpp │ ├── All Possible Full Binary Trees.cpp │ ├── Arithmetic Slices II - Subsequence.cpp │ ├── Arithmetic Slices.cpp │ ├── As Far from Land as Possible.cpp │ ├── Beautiful Arrangement.cpp │ ├── Best Sightseeing Pair.cpp │ ├── Best Time to Buy and Sell Stock II.cpp │ ├── Best Time to Buy and Sell Stock III.cpp │ ├── Best Time to Buy and Sell Stock IV.cpp │ ├── Best Time to Buy and Sell Stock with Cooldown.cpp │ ├── Best Time to Buy and Sell Stock with Transaction Fee.cpp │ ├── Best Time to Buy and Sell Stock.cpp │ ├── Binary Tree Maximum Path Sum.cpp │ ├── Binary Trees With Factors.cpp │ ├── Build Array Where You Can Find The Maximum Exactly K Comparisons.cpp │ ├── Burst Balloons.cpp │ ├── Can I Win.cpp │ ├── Champagne Tower.cpp │ ├── Cheapest Flights Within K Stops.cpp │ ├── Cherry Pickup.cpp │ ├── Climbing Stairs.cpp │ ├── Closest Dessert Cost.cpp │ ├── Closest Subsequence Sum.cpp │ ├── Coin Change 2.cpp │ ├── Coin Change.cpp │ ├── Combination Sum IV.cpp │ ├── Count All Valid Pickup and Delivery Options.cpp │ ├── Count Different Palindromic Subsequences.cpp │ ├── Count Number of Teams.cpp │ ├── Count Numbers with Unique Digits.cpp │ ├── Count Square Submattrices with All Ones.cpp │ ├── Count Submatrices With All Ones.cpp │ ├── Count Substrings That Differ by One Character.cpp │ ├── Count Subtrees With Max Distance Between Cities.cpp │ ├── Count The Repetitions.cpp │ ├── Count Vovels Permutation.cpp │ ├── Count Vowels Permutation.cpp │ ├── Count Ways to Build Rooms in an Ant Colony.cpp │ ├── Count all Possible Routes.cpp │ ├── Counting Bits.cpp │ ├── Decode Ways II.cpp │ ├── Decode Ways.cpp │ ├── Delete Columns to Make Sorted III.cpp │ ├── Delete Columns to Make Sorted.cpp │ ├── Delete Operation for Two Strings.cpp │ ├── Delete and Earn.cpp │ ├── Different Ways to Add Parentheses.cpp │ ├── Distinct Subsequences.cpp │ ├── Divisor Game.cpp │ ├── Domino and Tromino Tiling.cpp │ ├── Dungeon Game.cpp │ ├── Edit Distance.cpp │ ├── Egg Drop With 2 Eggs and N Floors.cpp │ ├── Fibonacci Number.cpp │ ├── Filling Bookcase Shelves.cpp │ ├── Find and Replace Pattern.cpp │ ├── Find the City With the Smallest Number of Neighbors at a Threshold Distance.cpp │ ├── Flip String to Monotone Increasing.cpp │ ├── Freedom Trail.cpp │ ├── Frog Jump.cpp │ ├── Generate Parentheses.cpp │ ├── Greatest Sum Divisible by Three.cpp │ ├── Guess Number Higher or Lower II.cpp │ ├── House Robber II.cpp │ ├── House Robber III.cpp │ ├── House Robber.cpp │ ├── Integer Break.cpp │ ├── Integer Replacement.cpp │ ├── Interleaving String.cpp │ ├── Is Subsequence.cpp │ ├── Jump Game II.cpp │ ├── Jump Game V.cpp │ ├── Jump Game.cpp │ ├── K Inverse Pairs Array.cpp │ ├── K-Concatenation Maximum Sum.cpp │ ├── Knight Dialer.cpp │ ├── Knight Probability in Chessboard.cpp │ ├── Kth Ancestor of a Tree Node.cpp │ ├── Kth Smallest Instructions.cpp │ ├── Largest 1-Bordered Square.cpp │ ├── Largest Divisible Subset.cpp │ ├── Largest Plus Sign.cpp │ ├── Largest Sum of Averages.cpp │ ├── Last Stone Weight II.cpp │ ├── Length of Longest Fibonacci Subsequence.cpp │ ├── Longest Arithmetic Subsequence of Given Difference.cpp │ ├── Longest Arithmetic Subsequence.cpp │ ├── Longest Chunked Palindrome Decomposition.cpp │ ├── Longest Common Subsequence.cpp │ ├── Longest Increasing Path in a Matrix.cpp │ ├── Longest Increasing Subsequence.cpp │ ├── Longest Palindromic Subsequence.cpp │ ├── Longest Palindromic Substring.cpp │ ├── Longest String Chain.cpp │ ├── Longest Subarray of 1's After Deleting One Element.cpp │ ├── Longest Turbulent Subarray.cpp │ ├── Longest Valid Parentheses.cpp │ ├── Longest ZigZag Path in a Binary Tree.cpp │ ├── Matchsticks to Square.cpp │ ├── Matrix Block Sum.cpp │ ├── Max Sum of Rectangle No Larger Than K.cpp │ ├── Maximal Rectangle.cpp │ ├── Maximal Square.cpp │ ├── Maximum Absolute Sum of Any Subarray.cpp │ ├── Maximum Alternating Subsequence Sum.cpp │ ├── Maximum Compatibility Score Sum.cpp │ ├── Maximum Length of Pair Chain.cpp │ ├── Maximum Length of Repeated Subarray.cpp │ ├── Maximum Length of Subarray With Positive Product.cpp │ ├── Maximum Number of Points with Cost.cpp │ ├── Maximum Product Subarray.cpp │ ├── Maximum Product of the Length of Two Palindromic Subsequences.cpp │ ├── Maximum Score Words Formed by Letters.cpp │ ├── Maximum Score from Performing Multiplication Operations.cpp │ ├── Maximum Students Taking Exam.cpp │ ├── Maximum Subarray Sum with One Deletion.cpp │ ├── Maximum Subarray.cpp │ ├── Maximum Sum BST in Binary Tree.cpp │ ├── Maximum Sum Circular Subarray.cpp │ ├── Maximum Sum of 3 Non-Overlapping Subarrays.cpp │ ├── Maximum Sum of Two Non-Overlapping Subarrays.cpp │ ├── Min Cost Climbing Stairs.cpp │ ├── Minimize the Difference Between Target and Chosen Elements.cpp │ ├── Minimum ASCII Delete Sum for Two Strings.cpp │ ├── Minimum Cost For Tickets.cpp │ ├── Minimum Cost Tree From Leaf Values.cpp │ ├── Minimum Cost to Cut a Stick.cpp │ ├── Minimum Cost to Merge Stones.cpp │ ├── Minimum Deletion Cost to Avoid Repeating Letters.cpp │ ├── Minimum Deletions to Make String Balanced.cpp │ ├── Minimum Difficulty of a Job Schedule.cpp │ ├── Minimum Distance to Type a Word Using Two Fingers.cpp │ ├── Minimum Falling Path Sum II.cpp │ ├── Minimum Falling Path Sum.cpp │ ├── Minimum Number of Increments on Subarrays to Form a Target Array.cpp │ ├── Minimum One Bit Operations to Make Integers Zero.cpp │ ├── Minimum Path Sum.cpp │ ├── Minimum Score Triangulation of Polygon.cpp │ ├── Minimum Sideway Jumps.cpp │ ├── Minimum Swaps To Make Sequences Increasing.cpp │ ├── N-th Tribonacci Number.cpp │ ├── Nearest Exit from Entrance in Maze.cpp │ ├── Non-negative Integers without Consecutive Ones.cpp │ ├── Non-overlapping Intervals.cpp │ ├── Number of Dice Rolls With Target Sum.cpp │ ├── Number of Good Ways to Split a String.cpp │ ├── Number of Longest Increasing Subsequence.cpp │ ├── Number of Smooth Descent Periods of a Stock.cpp │ ├── Number of Sub-arrays With Odd Sum.cpp │ ├── Number of Submattrices That Sum to Target.cpp │ ├── Number of Ways of Cutting a Pizza.cpp │ ├── Number of Ways to Arrive at Destination.cpp │ ├── Number of Ways to Separate Numbers.cpp │ ├── Number of Ways to Stay in the Same Place After Some Steps.cpp │ ├── Number of Ways to paint NX3 Grid.cpp │ ├── Ones and Zeroes.cpp │ ├── Optimal Division.cpp │ ├── Out of Boundary Paths.cpp │ ├── Painting a Grid With Three Different Colors.cpp │ ├── Palindrome Partitioning II.cpp │ ├── Palindrome Partitioning III.cpp │ ├── Palindrome Partitioning.cpp │ ├── Palindromic Substrings.cpp │ ├── Parallel Courses II.cpp │ ├── Partition Array Into Two Arrays to Minimize Sum Difference.cpp │ ├── Partition Array for Maximum Sum.cpp │ ├── Partition Equal Subset Sum.cpp │ ├── Partition to K Equal Sum Subsets.cpp │ ├── Pascal's Triangle II.cpp │ ├── Pascal's Triangle.cpp │ ├── Perfect Squares.cpp │ ├── Predict the Winner.cpp │ ├── Push Dominoes.cpp │ ├── Range Sum Query - Immutable.cpp │ ├── Regular Expression Matching.cpp │ ├── Remove Boxes.cpp │ ├── Rotate Function.cpp │ ├── Rotated Digits.cpp │ ├── Russian Doll Envelopes.cpp │ ├── Scramble String.cpp │ ├── Shopping Offers.cpp │ ├── Shortest Common Supersequence.cpp │ ├── Smallest Missing Genetic Value in Each Subtree.cpp │ ├── Sort Integers by The Power Value.cpp │ ├── Split Array Largest Sum.cpp │ ├── Split Array With Same Average.cpp │ ├── Stickers to Spell Word.cpp │ ├── Stone Game II.cpp │ ├── Stone Game III.cpp │ ├── Stone Game IV.cpp │ ├── Stone Game VII.cpp │ ├── Stone Game.cpp │ ├── Strange Printer.cpp │ ├── Student Attendance Record II.cpp │ ├── Sum of Distances in Tree.cpp │ ├── Sum of Subarray Minimums.cpp │ ├── Super Egg Drop.cpp │ ├── Super Ugly Number.cpp │ ├── Tallest Billboard.cpp │ ├── Target Sum.cpp │ ├── The Number of Good Subsets.cpp │ ├── The Score of Students Solving Math Expression.cpp │ ├── Trapping Rain Water.cpp │ ├── Triangle.cpp │ ├── Triples With Bitwise And Equal to Zero.cpp │ ├── Ugly Number II.cpp │ ├── Uncrossed Lines.cpp │ ├── Unique Binary Search Trees II.cpp │ ├── Unique Binary Search Trees.cpp │ ├── Unique Paths II.cpp │ ├── Unique Paths.cpp │ ├── Valid Parenthesis String.cpp │ ├── Valid Permutations for DI Sequence.cpp │ ├── Video Stitching.cpp │ ├── Vowels of All Substrings.cpp │ ├── Where Will the Ball Fall.cpp │ ├── Wiggle Subsequence.cpp │ ├── Wildcard Matching.cpp │ ├── Word Break II.cpp │ ├── Word Break.cpp │ └── readme.txt ├── MashupGalenColin │ ├── A.cpp │ ├── B.cpp │ ├── C.cpp │ ├── D.cpp │ ├── E.cpp │ ├── F.cpp │ ├── G.cpp │ ├── H.cpp │ ├── I.cpp │ ├── K.cpp │ ├── L.cpp │ ├── O.cpp │ └── readme.txt └── Standard DP Problems │ ├── SOS_DP_submask_count_queries.cpp │ ├── SOS_DP_supermask_count_queries.cpp │ └── Subgraph_in_treeDP.cpp ├── FFT ├── FFT_cyclicProd.cpp ├── FFT_matchBoolStripes.cpp ├── FFT_multiply.cpp ├── FFT_pairSum.cpp └── readme.txt ├── Graph Problems ├── 1324 F Subgraph in a tree DP.cpp ├── 1537F.cpp └── CSES │ ├── 1192 Counting Rooms.cpp │ ├── 1193 Labyrinth.cpp │ ├── 1194 Monsters.cpp │ ├── 1195 Flight Discount.cpp │ ├── 1196 Flight Routes.cpp │ ├── 1197 Cycle Finding.cpp │ ├── 1202 Investigation.cpp │ ├── 1666 Building Roads.cpp │ ├── 1667 Message Route.cpp │ ├── 1668 Building Teams.cpp │ ├── 1669 Round Trip.cpp │ ├── 1671 Shortest Routes I.cpp │ ├── 1672 Shortest Routes II.cpp │ ├── 1673 High Score.cpp │ ├── 1675 Road Reparation.cpp │ ├── 1676 Road Construction.cpp │ ├── 1678 Round Trip II.cpp │ ├── 1679 Course Schedule.cpp │ ├── 1680 Longest Flight Route.cpp │ ├── 1681 Game Routes.cpp │ ├── 1682 Flight Routes Check.cpp │ ├── 1683 Planets and Kingdoms.cpp │ ├── 1686 Coin Collector.cpp │ ├── 1689 Knight's Tour.cpp │ ├── 1690 Hamiltonian Flights.cpp │ ├── 1691 Mail Delivery.cpp │ ├── 1693 Teleporters Path.cpp │ ├── 1694 Download Speed.cpp │ ├── 1695 Police Chase.cpp │ ├── 1696 School Dance.cpp │ ├── 1750 Planets Queries I.cpp │ └── 1751 Planets Cycles.cpp ├── Hiring Round Problems ├── BlogVault_oncampus.md ├── CashFree_oncampus.md ├── Codenation_14_Aug_2021.md ├── Codenation_oncampus.md ├── DeutscheBank_oncampus.md ├── Mathworks_oncampus.md ├── MindTickle_oncampus.md └── readme.md ├── Interview Prep └── Google │ ├── AVL Tree implementation.cpp │ ├── AfterAcademy │ ├── 1. Roman To Integer.cpp │ ├── 10. Set Matrix Zeroes.cpp │ ├── 11. maximum j – i such that A[j] > A[i].cpp │ ├── 12. Move zeroes to an end.cpp │ ├── 13. Merge two sorted arrays.cpp │ ├── 14. Container with Most Water.cpp │ ├── 15. Remove duplicates from sorted array.cpp │ ├── 16. Find an element in Bitonic array.cpp │ ├── 17. Find minimum element in sorted and rotated array.cpp │ ├── 18. Median of two sorted array of same size.cpp │ ├── 19. Inversion count in an array.cpp │ ├── 2. Reverse Bits.cpp │ ├── 20. Search for a Range in a sorted array.cpp │ ├── 21. Longest Common Prefix.cpp │ ├── 22. Median in row wise sorted matrix.cpp │ ├── 23. Swap List Nodes in pairs.cpp │ ├── 24. Add Two Numbers as Lists.cpp │ ├── 25. Check if a singly linked list is palindrome.cpp │ ├── 26. Reverse a linked list from position m to n.cpp │ ├── 27. Detect and Remove Loop in a Linked List.cpp │ ├── 28. Merge Two Sorted Lists.cpp │ ├── 29. Remove Nth Node from List End.cpp │ ├── 3. Square Root of Integer.cpp │ ├── 30. Sort a linked list using insertion sort.cpp │ ├── 31. Find next greater element in an array.cpp │ ├── 32. Trapping rain water.cpp │ ├── 33. Merge overlapping intervals.cpp │ ├── 34. Largest Rectangle in Histogram.cpp │ ├── 35. Check for balanced parentheses in an expression.cpp │ ├── 36. Min Stack Problem.cpp │ ├── 37. LRU Cache implementation.cpp │ ├── 38. Sort a stack using another stack.cpp │ ├── 39. Lowest Common Ancestor of a Binary tree.cpp │ ├── 4. Calculate power function.cpp │ ├── 40. Path sum in binary tree.cpp │ ├── 5. Greatest Common Divisor.cpp │ ├── 6. Find the Closest Palindrome.cpp │ ├── 7. Rotate matrix.cpp │ ├── 8. Spiral Matrix.cpp │ └── 9. Wave Array.cpp │ ├── Binary Search Tree implementation.cpp │ ├── Delete Nodes And Return Forest.cpp │ ├── Expressive Words.cpp │ ├── Find the Closest Palindrome.cpp │ ├── Guess the Word.cpp │ ├── Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit.cpp │ ├── Sliding Window Maximum.cpp │ ├── The Skyline Problem.cpp │ └── Validate Stack Sequences.cpp ├── LCA Problems ├── 1535E.cpp └── 1541 D.cpp ├── Leetcode DBMS ├── Consecutive Numbers.mysql ├── Delete Duplicate Emails.mysql ├── Department Highest Salary.mysql ├── Department Top Three Salaries.mysql ├── Duplicate Emails.mysql ├── Employees Earning More Than Their Managers.mysql └── Nth Highest Salary.mysql ├── Leetcode Daily Challenges ├── 01 Matrix.cpp ├── 132 Pattern.cpp ├── 3Sum Closest.cpp ├── 3Sum With Multiplicity.cpp ├── 3Sum.cpp ├── 4Sum II.cpp ├── 4Sum.cpp ├── Accounts Merge.cpp ├── Add Binary.cpp ├── Add Digits.cpp ├── Add Strings.cpp ├── Add Two Numbers.cpp ├── All Elements in Two Binary Search Trees.cpp ├── All Paths From Source to Target.cpp ├── Arithmetic Slices II - Subsequence.cpp ├── Arithmetic Slices.cpp ├── Arranging Coins.cpp ├── Array Nesting.cpp ├── Array of Doubled Pairs.cpp ├── Backspace String Compare.cpp ├── Baseball Game.cpp ├── Basic Calculator II.cpp ├── Basic Calculator.cpp ├── Beautiful Array ├── Best Time to Buy and Sell Stock II.cpp ├── Best Time to Buy and Sell Stock III.cpp ├── Best Time to Buy and Sell Stock.cpp ├── Binary Search Tree Iterator.cpp ├── Binary Search.cpp ├── Binary Tree Pruning.cpp ├── Binary Tree Tilt.cpp ├── Bitwise AND of Numbers Range.cpp ├── Boats to Save People.cpp ├── Break a Palindrome.cpp ├── Broken Calculator.cpp ├── Burst Balloons.cpp ├── Can Place Flowers.cpp ├── Car Pooling.cpp ├── Champagne Tower.cpp ├── Check If a String Contains All Binary Codes of Size K.cpp ├── Cherry Pickup II.cpp ├── Climbing Stairs.cpp ├── Clone Graph.cpp ├── Coin Change.cpp ├── Combination Sum III.cpp ├── Combination Sum.cpp ├── Compare Version Numbers.cpp ├── Complement of Base 10 Integer.cpp ├── Complex Number Multiplication.cpp ├── Consecutive Characters.cpp ├── Construct Binary Search Tree from Preorder Traversal.cpp ├── Construct Binary Tree from Inorder and Postorder Traversal.cpp ├── Contiguous Array.cpp ├── Convert BST to Greater Tree.cpp ├── Convert Binary Number in a Linked List to Integer.cpp ├── Convert Sorted Array to Binary Search Tree.cpp ├── Count All Valid Pickup and Delivery Options.cpp ├── Count Complete Tree Nodes.cpp ├── Count Good Nodes in Binary Tree.cpp ├── Count Sorted Vowel Strings.cpp ├── Counting Bits.cpp ├── Course Schedule II.cpp ├── Cousins in Binary Tree.cpp ├── Critical Connections in a Network.cpp ├── Custom Sort String.cpp ├── Daily Temperatures.cpp ├── Decode String.cpp ├── Decode Ways.cpp ├── Deepest Leaves Sum.cpp ├── Delete Node in a BST.cpp ├── Delete Operation for Two Strings.cpp ├── Delete and Earn.cpp ├── Design Add and Search Words Data Structure.cpp ├── Design HashMap.cpp ├── Design HashSet.cpp ├── Design Underground System.cpp ├── Detect Capital.cpp ├── Diameter of Binary Tree.cpp ├── Distinct Subsequences.cpp ├── Divide Two Integers.cpp ├── Domino and Tromino Tiling.cpp ├── Dungeon Game.cpp ├── Encode and Decode TinyURL.cpp ├── Evaluate Division.cpp ├── Excel Sheet Column Number.cpp ├── Find All Anagrams in a String.cpp ├── Find All Duplicates in an Array.cpp ├── Find All Numbers Disappeared in an Array.cpp ├── Find Median from Data Stream.cpp ├── Find Minimum in Rotated Sorted Array II.cpp ├── Find Minimum in Rotated Sorted Array.cpp ├── Find Peak Element.cpp ├── Find Winner on a Tic Tac Toe Game.cpp ├── Find a Corresponding Node of a Binary Tree in a Clone of That Tree.cpp ├── Find the Difference.cpp ├── Find the Duplicate Number.cpp ├── Find the Town Judge.cpp ├── Flatten a Multilevel Doubly Linked List.cpp ├── Flip String to Monotone Increasing.cpp ├── Game of Life.cpp ├── Gas Station.cpp ├── Group Anagrams.cpp ├── Guess Number Higher or Lower.cpp ├── Hamming Distance.cpp ├── House Robber III.cpp ├── House Robber.cpp ├── Implement Stack using Queues.cpp ├── Implement Trie (Prefix Tree).cpp ├── Insert Delete GetRandom O(1).cpp ├── Insert into a Binary Search Tree.cpp ├── Insertion Sort List.cpp ├── Intersection of Two Arrays II.cpp ├── Intersection of Two Linked Lists.cpp ├── Interval List Intersections.cpp ├── Invert Binary Tree.cpp ├── Is Graph Bipartite?.cpp ├── Is Subsequence.cpp ├── Isomorphic Strings.cpp ├── Iterator for Combination.cpp ├── Jump Game III.cpp ├── Jump Game IV.cpp ├── Jump Game.cpp ├── K Closest Points to Origin.cpp ├── K-diff Pairs in an Array.cpp ├── Koko Eating Bananas.cpp ├── Kth Largest Element in a Stream.cpp ├── Kth Largest Element in an Array.cpp ├── Kth Smallest Element in a BST.cpp ├── Kth Smallest Number in Multiplication Table.cpp ├── Largest Component Size by Common Factor.cpp ├── Largest Divisible Subset.cpp ├── Largest Plus Sign.cpp ├── Largest Rectangle in Histogram.cpp ├── Last Stone Weight.cpp ├── Letter Combinations of a Phone Number.cpp ├── Linked List Cycle II.cpp ├── Linked List Cycle.cpp ├── Linked List Random Node.cpp ├── Longest Common Subsequence.cpp ├── Longest Duplicate Substring.cpp ├── Longest Increasing Path in a Matrix.cpp ├── Longest Increasing Subsequence Solution.cpp ├── Longest Palindromic Substring.cpp ├── Longest String Chain.cpp ├── Longest Substring Without Repeating Characters.cpp ├── Longest Turbulent Subarray.cpp ├── Longest Uncommon Subsequence II.cpp ├── Longest Valid Parentheses.cpp ├── Lowest Common Ancestor of a Binary Search Tree.cpp ├── Majority Element.cpp ├── Making A Large Island.cpp ├── Max Consecutive Ones.cpp ├── Max Number of K-Sum Pairs.cpp ├── Maximal Rectangle.cpp ├── Maximal Square.cpp ├── Maximize Distance to Closest Person.cpp ├── Maximum Depth of Binary Tree.cpp ├── Maximum Difference Between Node and Ancestor.cpp ├── Maximum Erasure Value.cpp ├── Maximum Length of a Concatenated String with Unique Characters.cpp ├── Maximum Number of Balloons.cpp ├── Maximum Product Subarray.cpp ├── Maximum Product of Splitted Binary Tree.cpp ├── Maximum Product of Word Lengths.cpp ├── Maximum Profit in Job Scheduling.cpp ├── Maximum Subarray.cpp ├── Maximum Width of Binary Tree.CPP ├── Maximum XOR of Two Numbers in an Array.cpp ├── Merge Intervals.cpp ├── Merge Sorted Array.cpp ├── Merge Two Sorted Lists.cpp ├── Merge k Sorted Lists.cpp ├── Middle of the Linked List.cpp ├── Min Stack.cpp ├── Minimize Deviation in Array.cpp ├── Minimum Absolute Difference.cpp ├── Minimum Cost to Move Chips to The Same Position.cpp ├── Minimum Domino Rotations For Equal Row.cpp ├── Minimum Height Trees.cpp ├── Minimum Number of Arrows to Burst Balloons.cpp ├── Minimum Value to Get Positive Step by Step Sum.cpp ├── Minimum Window Substring.cpp ├── Missing Number.cpp ├── Multiply Strings.cpp ├── N-Queens II.cpp ├── N-Queens.cpp ├── N-ary Tree Level Order Traversal.cpp ├── N-th Tribonacci Number.cpp ├── Network Delay Time.cpp ├── Next Greater Element I.cpp ├── Next Permutation.cpp ├── Non-negative Integers without Consecutive Ones.cpp ├── Nth Magical Number.cpp ├── Number Complement.cpp ├── Number of 1 Bits.cpp ├── Number of Steps to Reduce a Number to Zero.cpp ├── Number of Valid Words for Each Puzzle.cpp ├── Odd Even Linked List.cpp ├── Ones and Zeroes.cpp ├── Orderly Queue.cpp ├── Pairs of Songs With Total Durations Divisible by 60.cpp ├── Palindrome Partitioning II.cpp ├── Palindrome Partitioning.cpp ├── Palindromic Substrings.cpp ├── Partition Array into Disjoint Intervals.cpp ├── Partition Equal Subset Sum.cpp ├── Partition Labels.cpp ├── Partition to K Equal Sum Subsets.cpp ├── Patching Array.cpp ├── Path Sum II.cpp ├── Path Sum III.cpp ├── Peeking Iterator.cpp ├── Perfect Squares.cpp ├── Permutation in String.cpp ├── Permutations II.cpp ├── Populating Next Right Pointers in Each Node II.cpp ├── Populating Next Right Pointers in Each Node.cpp ├── Power of Two.cpp ├── Prefix and Suffix Search.cpp ├── Product of Array Except Self.cpp ├── Push Dominoes.cpp ├── Range Addition II.cpp ├── Range Sum Query - Immutable.cpp ├── Range Sum Query 2D - Immutable.cpp ├── Range Sum of BST.cpp ├── Reachable Nodes In Subdivided Graph.cpp ├── Recover Binary Search Tree.cpp ├── Rectangle Area II.cpp ├── Remove All Adjacent Duplicates in String II.cpp ├── Remove Boxes.cpp ├── Remove Covered Intervals.cpp ├── Remove Duplicates from Sorted Array II.cpp ├── Remove Duplicates from Sorted List II.cpp ├── Remove K Digits.cpp ├── Remove Linked List Elements.cpp ├── Remove Palindromic Subsequences.cpp ├── Reorder List.cpp ├── Reverse Linked List.cpp ├── Reverse Only Letters.cpp ├── Reverse String.cpp ├── Reverse Words in a String.cpp ├── Richest Customer Wealth.cpp ├── Robot Bounded In Circle.cpp ├── Rotate Array.cpp ├── Rotate List.cpp ├── Rotting Oranges.cpp ├── Running Sum of 1d Array.cpp ├── Russian Doll Envelopes.cpp ├── Score of Parentheses.cpp ├── Search Insert Position.cpp ├── Search a 2D Matrix.cpp ├── Search in Rotated Sorted Array II.cpp ├── Search in a Binary Search Tree.cpp ├── Sequential Digits.cpp ├── Set Matrix Zeroes.cpp ├── Shifting Letters.cpp ├── Shortest Path Visiting All Nodes.cpp ├── Shortest Path in Binary Matrix.cpp ├── Shortest Path in a Grid with Obstacles Elimination.cpp ├── Shuffle an Array.cpp ├── Single Element in a Sorted Array.cpp ├── Single Number III.cpp ├── Single Number.cpp ├── Slowest Key.cpp ├── Smallest Integer Divisible by K.cpp ├── Smallest String With A Given Numeric Value.cpp ├── Sort Array By Parity II.cpp ├── Sort Array By Parity.cpp ├── Sort Characters By Frequency.cpp ├── Sort Colors.cpp ├── Sort List.cpp ├── Spiral Matrix II.cpp ├── Split Array Largest Sum.cpp ├── Split Linked List in Parts.cpp ├── Stone Game IV.cpp ├── Stone Game.cpp ├── Stream of Characters.cpp ├── String to Integer (atoi).cpp ├── Subarray Sum Equals K.cpp ├── Subsets II.cpp ├── Subsets.cpp ├── Sudoku Solver.cpp ├── Sum Root to Leaf Numbers.cpp ├── Sum of Distances in Tree.cpp ├── Sum of Left Leaves.cpp ├── Sum of Root To Leaf Binary Numbers.cpp ├── Sum of Square Numbers.cpp ├── Summary Ranges.cpp ├── Surrounded Regions.cpp ├── Swap Nodes in Pairs.cpp ├── The K Weakest Rows in a Matrix.cpp ├── Top K Frequent Elements.cpp ├── Transform to Chessboard.cpp ├── Transpose Matrix.cpp ├── Triangle.cpp ├── Trim a Binary Search Tree.cpp ├── Two City Scheduling.cpp ├── Two Sum II - Input Array Is Sorted.cpp ├── Two Sum IV - Input is a BST.cpp ├── Two Sum.cpp ├── Unique Binary Search Trees II.cpp ├── Unique Binary Search Trees.cpp ├── Unique Email Addresses.cpp ├── Unique Paths II.cpp ├── Unique Paths III.cpp ├── Unique Paths.cpp ├── Valid Mountain Array.cpp ├── Valid Palindrome II.cpp ├── Valid Parentheses.cpp ├── Valid Sudoku.cpp ├── Valid Triangle Number.cpp ├── Validate Stack Sequences.cpp ├── Verify Preorder Serialization of a Binary Tree.cpp ├── Word Ladder.cpp ├── Word Pattern.cpp ├── Word Search II.cpp └── Word Search.cpp ├── README.md ├── Standard BIT problems ├── 1073-D.cpp └── 1520F2.cpp ├── Standard DSU Problems └── 455 C.cpp ├── Standard FFT Problems ├── SPOJ_POLYMUL.cpp └── readme.txt ├── Standard Matrix Exponentiation ├── CC_ECODOWN_Non_Linear_to_Linear.cpp └── Fibonacci.cpp ├── Standard Min Cut Max Flow Problems └── maxflow CSES 1694.cpp ├── Standard SegTree Problems ├── Nested segments.cpp ├── addLR_get.cpp ├── add_sum.cpp ├── addition_to_segment.cpp ├── alternate_sign_sum_assign.cpp ├── and_or_query.cpp ├── assignLR_get.cpp ├── assignment_min.cpp ├── assignment_sum.cpp ├── distinctLRsmallN.cpp ├── firstAtleastX_set.cpp ├── firstGreaterThanKinLR.cpp ├── intersecting_segments_with_each_segment.cpp ├── intervalSubset 1555.cpp ├── inverse_kthOne.cpp ├── inversion2.cpp ├── inversions.cpp ├── inversionsLRsmallN.cpp ├── kth_one.cpp ├── lower_bound_set.cpp ├── majority_elementLR.cpp ├── maxLR_get.cpp ├── max_sum_segment_set.cpp ├── maximalSeg_setLR.cpp ├── min_count_set_query.cpp ├── min_set_query.cpp ├── readme.txt ├── sum_min_query.cpp ├── sum_mul_query.cpp └── sum_set_query.cpp ├── Standard Trie Problems ├── MaxXOR_set_queries.cpp └── Maximum XOR of Two Numbers in an Array.cpp ├── Standard smallToLargeMerge Problems ├── distinctInSubtree.cpp └── sumOfMajorityColorInSubtree 600E.cpp ├── StandardTreapProblems └── split_merge_queries.cpp └── Templates ├── 2 Sat.cpp ├── Articulation_points.cpp ├── BIT.cpp ├── BIT1D.cpp ├── BIT2D.cpp ├── BinaryLifting.cpp ├── DSU.cpp ├── FFT_template.cpp ├── Graham Scan Convex Hull.cpp ├── Heavy Light Decomposition (HLD).cpp ├── KMP+PrefixFunction.cpp ├── LLE_LGE_RGE_RLE.cpp ├── MatrixTemplate.cpp ├── Max Flow Edmonds-Karp.cpp ├── RollingHash.cpp ├── SOS DP.cpp ├── SPF_NCR_TotientFunction_ExtendedEuclidean_Divisors_DivSum.cpp ├── Strongly_connected_componentsKosaraju.cpp ├── TopSortKahn.cpp ├── Tree_diameter_with_ends.cpp ├── binaryLifting.cpp ├── bitPBDS.cpp ├── bridges.cpp ├── centroidDecomposition1.cpp ├── centroidDecomposition2.cpp ├── dateTimeTemplate.cpp ├── dijkstraUsingPriorityQueue.cpp ├── dijkstraUsingSet.cpp ├── modIntTemplate.cpp ├── mst_kruskal.cpp ├── readme.txt ├── segTreeAshishgup.cpp ├── segTreeSmall.cpp ├── segTreeSmallWithLazyProp.cpp ├── segTreeTemplate.cpp ├── smallToLargeMerge.cpp └── sparseTableTemplate.cpp /CSES/Tree/readme.md: -------------------------------------------------------------------------------- 1 | https://cses.fi/problemset/list/ 2 | -------------------------------------------------------------------------------- /CSES/readme.md: -------------------------------------------------------------------------------- 1 | ### CSES GRAPH SECTION: [Graph Problems/CSES](../Graph%20Problems/CSES) 2 | ### CSES DP SECTION: [Dynamic Programming/CSES](../Dynamic%20Programming/CSES) 3 | -------------------------------------------------------------------------------- /Contests/Credit Suisse Global Coding Challenge 2021/Question1.c: -------------------------------------------------------------------------------- 1 | #include 2 | #define gc getchar_unlocked 3 | int main(void) { 4 | register int x = 0, c = gc(); 5 | while(c != -1) { 6 | x = (x << 1) + (x << 3) + c - 48; 7 | c = gc(); 8 | } 9 | printf("%d",((x << 1)+ 1)/3); 10 | return 0; 11 | } 12 | -------------------------------------------------------------------------------- /Contests/Credit Suisse Global Coding Challenge 2021/readme.md: -------------------------------------------------------------------------------- 1 | # Credit Suisse Global Coding Challenge 2021 2 | 3 | These are my (@notabhishek) solutions that gave the maximum points, there were many others versions that gave same amount of points but these were my final submissions. 4 | 5 | Contest link: [GCC 2021](https://www.credit-suisse.com/pwp/hr/en/codingchallenge/#/home) 6 | #### Points at the time of contest: 7 | Total : 886 [99, 99, 99, 98, 99, 98, 97, 99, 98] 8 | #### Points after rejudging: 9 | Total : 885.619177653434 10 | #### Final rank: 1 11 | 12 | Connect with me here in case you have any queries: [LinkedIn](https://www.linkedin.com/in/notabhishek/) 13 | -------------------------------------------------------------------------------- /Dynamic Programming/Atcoder Educational DP Contest/readme.txt: -------------------------------------------------------------------------------- 1 | Solutions to AtCoder Educational DP Contest Problems 2 | https://atcoder.jp/contests/dp 3 | -------------------------------------------------------------------------------- /Dynamic Programming/CSES/readme.txt: -------------------------------------------------------------------------------- 1 | Solutions of CSES Dp problems 2 | https://cses.fi/problemset/ 3 | -------------------------------------------------------------------------------- /Dynamic Programming/Digit DP/countOfNumbersWithDigitSum.cpp: -------------------------------------------------------------------------------- 1 | // numbers < R with given digitsum 2 | #include 3 | using namespace std; 4 | 5 | int dp[101][181][2]; // dp[length][dsum][tight] 6 | 7 | int solve(string &num, int n, int x, bool tight) { 8 | // base case 9 | if(n == 0) 10 | return x == 0; 11 | if(dp[n][x][tight] != -1) 12 | return dp[n][x][tight]; 13 | 14 | int ub = tight ? num[num.length()-n]-'0' : 9; 15 | int answer = 0; 16 | for(int dig = 0; dig <= ub; ++dig) { 17 | answer += solve(num, n-1, x-dig, tight & (dig == ub)); 18 | } 19 | 20 | return dp[n][x][tight] = answer; 21 | } 22 | 23 | int main() { 24 | 25 | string num; 26 | int dsum; 27 | cin >> num >> dsum; 28 | memset(dp, -1, sizeof dp); 29 | cout << solve(num, num.length(), dsum, 1); 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/2 Keys Keyboard.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int calc(int n , vector &steps ){ 4 | if(steps[n]!=-1) 5 | return steps[n]; 6 | steps[n] = INT_MAX; 7 | for(int i = 1; i < n; ++i) { 8 | if((n-i)%i == 0) 9 | steps[n] = min( steps[n] , calc(i , steps) + 1 + (n-i)/i ); 10 | } 11 | return steps[n]; 12 | } 13 | int minSteps(int n) { 14 | vector steps(n+1 , -1); 15 | steps[1] = 0; 16 | calc(n , steps); 17 | for(auto i : steps ) cout << i << " "; 18 | return steps[n]; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Airplane Seat Assignment Probability.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double nthPersonGetsNthSeat(int n) { 4 | double dp[n]; 5 | double pref[n]; 6 | dp[n-1] = 1; 7 | pref[n-1] = 1; 8 | for(int i = n-2;i >= 0; --i) { 9 | dp[i] = pref[i+1]; 10 | dp[i]/= (double)(n-i); 11 | pref[i] = pref[i + 1] + dp[i]; 12 | } 13 | return dp[0]; 14 | } 15 | }; -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Arithmetic Slices II - Subsequence.cpp: -------------------------------------------------------------------------------- 1 | using ll = long long; 2 | class Solution { 3 | public: 4 | int numberOfArithmeticSlices(vector& a) { 5 | int n = a.size(); 6 | int ans = 0; 7 | map< ll, int> dp[n]; 8 | // dp[i][ d ] = number of subseq ending at i, having difference d 9 | 10 | for(int i = 0; i < n; ++i) { 11 | for(int j = 0; j< i; ++j) { 12 | ll d = (ll)a[i] - (ll)a[j]; 13 | int cur = (dp[j].count(d) ? 1 + dp[j][d] : 1); 14 | dp[i][d] += cur; 15 | ans += cur; 16 | } 17 | } 18 | // subtract 2 length 19 | ans -= ((n-1)*(n))/2; 20 | return ans; 21 | 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Arithmetic Slices.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numberOfArithmeticSlices(vector& A) { 4 | int i = 2; 5 | int slices = 0; 6 | while(i < A.size()) { 7 | if((A[i] - A[i-1]) == (A[i-1]-A[i-2])) { 8 | int d = A[i] - A[i-1]; 9 | int cur = 0; 10 | while( i < A.size() && A[i] - A[i-1] == d) {++i; ++cur;} 11 | slices += (cur*(cur+1))/2; 12 | } else 13 | ++i; 14 | } 15 | return slices; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Beautiful Arrangement.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int N; 4 | vector< vector> dp; 5 | int cnt(int n, int mask) { 6 | if(mask == 0) 7 | return 1; 8 | if(dp[n][mask] != -1) 9 | return dp[n][mask]; 10 | dp[n][mask] = 0; 11 | for(int i = 0 ; i < N; ++i) { 12 | if( (mask & (1< ( 1<& a) { 4 | int mx = a[0] + 0; 5 | int ans = INT_MIN; 6 | for(int j = 1; j < a.size(); ++j) { 7 | ans = max(ans , a[j]-j + mx); 8 | mx = max(mx , a[j] + j); 9 | } 10 | return ans; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Best Time to Buy and Sell Stock II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector& prices) { 4 | int ans = 0; 5 | for(int i = 1; i < prices.size();++i ) ans+= max(0 , prices[i] - prices[i-1]); 6 | return ans; 7 | } 8 | }; 9 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Best Time to Buy and Sell Stock IV.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(int k, vector& prices) { 4 | if(k==0 || prices.size()==0) 5 | return 0; 6 | int n = prices.size(); 7 | if(k >= n/2) { 8 | int ans = 0 ; 9 | for(int i = 1 ; i < prices.size(); ++i) 10 | ans+= max(0 , prices[i] - prices[i-1]); 11 | return ans; 12 | } 13 | //DP 14 | vector cost(k+1 , prices[0]) , profit(k+1 , 0); 15 | for(int i = 1; i < n; ++i) { 16 | for(int j = 1; j<=k; ++j) { 17 | cost[j] = min(cost[j] , prices[i] - profit[j-1]); 18 | profit[j] = max(profit[j] , prices[i] - cost[j] ); 19 | } 20 | } 21 | return profit[k]; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Best Time to Buy and Sell Stock with Cooldown.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector& a) { 4 | int n = a.size(); 5 | int dp[n+1][2]; 6 | // dp[i][0] = max profit after selling on ith day 7 | // dp[i][1] = max profit not necessarily selling on ith day 8 | dp[0][0] = dp[0][1] = 0; 9 | for(int i = 1; i <= n; ++i){ 10 | dp[i][0] = dp[i][1] = 0; 11 | for(int j = i-1; j >= 1; --j) { 12 | dp[i][0] = max(dp[i][0] , a[i-1]-a[j-1] + (j>1 ? dp[j-2][1] : 0)); 13 | } 14 | dp[i][1] = max(dp[i-1][1] , dp[i][0]); 15 | } 16 | return dp[n][1]; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Best Time to Buy and Sell Stock with Transaction Fee.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector& a, int fee) { 4 | int hasStock = -a[0]; // max profit having 1 stock in hand 5 | int noStock = 0; // max profit having no stocks in hand 6 | for(int i = 0; i < a.size(); ++i) { 7 | noStock = max(noStock ,a[i] + hasStock-fee); //wait or sell the last stock in hand 8 | hasStock = max(hasStock, noStock - a[i]); // wait or sell and then buy new stock 9 | } 10 | return noStock; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Best Time to Buy and Sell Stock.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector& prices) { 4 | int ans = 0; 5 | int mn = INT_MAX; 6 | for(auto &i : prices ) { 7 | ans = max(ans , i - mn); 8 | mn = min(mn , i); 9 | } 10 | return ans; 11 | } 12 | }; -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Binary Trees With Factors.cpp: -------------------------------------------------------------------------------- 1 | using ll = long long; 2 | class Solution { 3 | public: 4 | const int MOD = 1e9 + 7; 5 | int numFactoredBinaryTrees(vector& a) { 6 | sort(a.begin() , a.end()); 7 | map dp; 8 | ll ans = 0 , n = a.size(); 9 | for(int i = 0; i < n; ++i) { 10 | ll cur = 1; 11 | for(int j = 0; j < i; ++j) { 12 | if(a[i] % a[j] == 0 && dp.count(a[i]/a[j])) 13 | cur = (cur + (dp[ a[j] ] * dp[a[i]/a[j]])%MOD)%MOD; 14 | } 15 | dp[a[i]] = cur; 16 | ans = (ans + cur) % MOD; 17 | } 18 | return ans; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Can I Win.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector dp; 4 | int bit; 5 | bool rec(int n, int mask) { 6 | if(n <= 0) return false; 7 | if(dp[mask] != -1) return dp[mask]; 8 | for(int i = 0; i < bit; ++i) { 9 | if((mask & (1<> dp(105 , vector (105,0)); 9 | dp[0][0] = poured; 10 | for(int row = 1; row <= 100; ++row) { 11 | for(int i = 0 ; i < row; ++i) { 12 | if(dp[row-1][i] > 1 ) { 13 | dp[row][i] += (dp[row-1][i] - 1)/2.00000000000; 14 | dp[row][i+1] += (dp[row-1][i] - 1)/2.00000000000; 15 | } 16 | } 17 | } 18 | double &res = dp[query_row][query_glass]; 19 | if(res > 1 ) res = 1; 20 | return res; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Climbing Stairs.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int climbStairs(int n) { 4 | int dp[n + 1]; 5 | dp[0] = 1; 6 | dp[1] = 1; 7 | for(int i = 2; i <= n; ++i) 8 | dp[i] = dp[i-1] + dp[i-2]; 9 | return dp[n]; 10 | } 11 | }; -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Coin Change 2.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | const int MOD = 1e9 + 7; 4 | vector> dp; 5 | int rec(int sum ,int c, vector& coins) { 6 | if(c< 0) 7 | return sum == 0; 8 | int &ret = dp[sum][c]; 9 | if(ret != -1) 10 | return ret; 11 | ret = rec(sum , c-1, coins); 12 | if(sum >= coins[c]) 13 | ret += rec(sum - coins[c], c, coins); 14 | // ret %= MOD; 15 | return ret; 16 | } 17 | int change(int amount, vector& coins) { 18 | int n = coins.size(); 19 | dp.resize(amount + 1 ,vector(n + 1, -1)); 20 | int ans = rec(amount, n-1, coins); 21 | return ans; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Coin Change.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int coinChange(vector& coins, int amount) { 4 | vector req(amount+1 , INT_MAX); 5 | req[0] = 0; 6 | for(auto &coin : coins) { 7 | for(int i = coin; i<=amount; ++i) 8 | if(req[i-coin]!=INT_MAX) 9 | req[i] = min(req[i] , 1 + req[i-coin]); 10 | } 11 | if(req[amount] == INT_MAX) 12 | return -1; 13 | return req[amount]; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Combination Sum IV.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector< int > dp; 4 | int msum; 5 | int rec(int sum, vector &a) { 6 | int &ret = dp[sum]; 7 | if(ret != -1) 8 | return ret; 9 | ret = 0; 10 | for(int i = 0; i < a.size(); ++i) { 11 | if(sum >= a[i]) 12 | ret += rec( sum - a[i] , a); 13 | } 14 | return ret; 15 | } 16 | int combinationSum4(vector& a, int sum) { 17 | int n = a.size(); 18 | dp.resize( sum + 1 , -1 ); 19 | dp[0] = 1; 20 | return rec(sum, a); 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Count All Valid Pickup and Delivery Options.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | const int MOD = 1e9 + 7; 5 | int sum(long long int n) { 6 | return ( ( (n+1) * n )/2) % MOD; 7 | } 8 | int countOrders(int n) { 9 | vector< long long int > dp(n + 1 , 0); 10 | dp[1] = 1; 11 | for(int i = 2; i <= n; ++i) { 12 | dp[i] = (dp[i-1] * sum(2 * i - 1) ) % MOD; 13 | } 14 | return (int)dp[n]; 15 | } 16 | }; -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Count Numbers with Unique Digits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countNumbersWithUniqueDigits(int n) { 4 | if( n == 0) 5 | return 1; 6 | int dp[9] ={0}; 7 | dp[0] = 1; 8 | for(int i = 1 ; i < 9; ++i) { 9 | int c = 9; 10 | for(int j = 1; j < i; ++j) 11 | c*= 10-j; 12 | dp[i] = dp[i-1] + c; 13 | } 14 | return dp[ n ]; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Counting Bits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector countBits(int num) { 4 | vector< int > res(num + 1 , 0); 5 | // for(int i = 0; i <= num; ++i) { 6 | // res[i] = __builtin_popcount(i); 7 | // } 8 | for(int i = 1; i <= num; ++i) { 9 | if( (i & (i-1) ) == 0 ) { 10 | res[i] = 1; 11 | } else { 12 | res[i] = 1 + res[i - (1 << (int) log2(i) )]; 13 | } 14 | } 15 | return res; 16 | } 17 | }; -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Decode Ways.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int ways(int i , string &s , vector &dp) { 4 | if(i==0) 5 | return 1; 6 | if(dp[i-1]!=-1) 7 | return dp[i-1]; 8 | dp[i-1] = 0; 9 | if(s[i-1]!='0') 10 | dp[i-1]+= ways(i-1 , s , dp); 11 | if((i-1)> 0) { 12 | if(s[i-2]=='1') dp[i-1] += ways(i-2 , s , dp); 13 | if(s[i-2]=='2' && s[i-1]<='6') dp[i-1]+=ways(i-2 , s , dp); 14 | } 15 | return dp[i-1]; 16 | } 17 | int numDecodings(string s) { 18 | vector dp(s.length() , -1); 19 | return ways(s.length() , s , dp); 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Delete Operation for Two Strings.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | // L1 + L2 - 2 * LCS 4 | vector< vector> dp; 5 | int lcs(int i , int j , string &a, string &b) { 6 | if(i < 0 || j < 0) 7 | return 0; 8 | int &ret = dp[i][j]; 9 | if(ret != -1) 10 | return ret; 11 | 12 | if(a[i] == b[j]) return ret = 1 + lcs(i-1, j-1, a ,b); 13 | return ret = max(lcs(i-1, j , a , b), lcs(i, j-1, a, b)); 14 | } 15 | int minDistance(string a, string b) { 16 | int n = a.size(); 17 | int m = b.size(); 18 | dp.resize(n , vector (m, -1)); 19 | return m + n - 2 * lcs(n-1, m-1, a, b); 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Delete and Earn.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int deleteAndEarn(vector& a) { 4 | int n = a.size(); 5 | sort(a.begin() , a.end()); 6 | // for(auto &i : a) cout << i << " "; cout << endl; 7 | vector dp(n + 1, 0); 8 | int ans = 0; 9 | for(int i = 1; i <= n; ++i) { 10 | // take this element 11 | dp[i] = a[i-1]; 12 | for(int j = i-1; j > 0; --j) 13 | if(a[j-1] != a[i-1]-1 && a[j-1]!=a[i-1]+1 ) 14 | dp[i] = max(dp[i] , a[i-1] + dp[j]); 15 | ans = max(ans , dp[i]); 16 | } 17 | // for(auto &i : dp) cout << i << " "; cout << endl; 18 | return ans; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Distinct Subsequences.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lcs(int i , int j , string &s , string &t , vector> &dp) { 4 | if(j==0) { 5 | return 1; 6 | } 7 | if(i==0) 8 | return 0; 9 | if(dp[i][j]!=-1) 10 | return dp[i][j]; 11 | int ans = 0; 12 | if(t[j-1] == s[i-1]) 13 | ans+= lcs(i-1 , j-1 , s , t , dp); 14 | ans+= lcs(i-1 , j , s, t , dp); 15 | dp[i][j] = ans; 16 | return ans; 17 | } 18 | int numDistinct(string s, string t) { 19 | vector> dp(s.length()+1 , vector (t.length()+1 , -1)); 20 | return lcs(s.length() , t.length() , s ,t , dp); 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Divisor Game.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool win(int N , vector< int > &dp) { 4 | if(dp[N] != -1) 5 | return dp[N]; 6 | for(int i = 2; i * i <= N; ++i ) { 7 | if( N % i == 0 ) { 8 | if(!win(N - i , dp) || !win(N - N/i , dp)) 9 | return dp[N] = true; 10 | } 11 | } 12 | if(!win(N-1 , dp)) 13 | return dp[N] = true; 14 | return dp[N] = false; 15 | } 16 | bool divisorGame(int N) { 17 | const int MXN = 1e3 + 5; 18 | vector< int > dp( MXN , -1 ); 19 | dp[1] = 0; 20 | return win(N , dp); 21 | } 22 | }; -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Egg Drop With 2 Eggs and N Floors.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | const int INF = 1e3; 4 | vector> dp; 5 | int rec(int n , int k) { 6 | if(n <=2 ) return n; 7 | if(k == 1) return n; 8 | int &ret = dp[k][n]; 9 | if(ret != -1) 10 | return ret; 11 | ret = n; 12 | for(int i = 1; i <= n; ++i) 13 | ret = min(ret ,1 + max(rec(i-1,k-1) , rec(n-i, k ))); 14 | return ret; 15 | } 16 | int twoEggDrop(int n) { 17 | int k = 2; 18 | dp.resize(k+1 , vector( n+1 , -1)); 19 | dp[1][1] = 0; 20 | int ans = rec(n, k); 21 | return ans; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Fibonacci Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int fib(int N) { 4 | if(N <= 1) 5 | return N; 6 | int p = 0 , q = 1; 7 | for(int i = 2 ; i <=N;++i) { 8 | int r = p+q; 9 | p = q; 10 | q = r; 11 | } 12 | return q; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Find and Replace Pattern.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool match(string &a, string &b){ 4 | vector f(26, -1); 5 | vector can(26, 1); 6 | for(int i = 0; i < b.length(); ++i) { 7 | if(f[b[i] - 'a'] == -1) { 8 | if(!can[ a[i]-'a' ]) return false; 9 | f[b[i]-'a'] = a[i]-'a'; 10 | can[ a[i] - 'a' ] = 0; 11 | } else if(f[b[i]-'a'] != (a[i] - 'a')) return false; 12 | } 13 | return true; 14 | } 15 | vector findAndReplacePattern(vector& words, string pattern) { 16 | vectorres; 17 | for(auto &w : words) { 18 | if(match(w, pattern)) 19 | res.push_back(w); 20 | } 21 | return res; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Flip String to Monotone Increasing.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minFlipsMonoIncr(string s) { 4 | int tz = count(s.begin() , s.end(), '0'); 5 | int n = s.length(); 6 | int to = n - tz; 7 | vector pre(n+1); 8 | pre[0] = 0; 9 | for(int i = 1; i <= n; ++i) pre[i] = pre[i-1] + (s[i-1]=='1'); 10 | int ans = tz; // make all ones 11 | // all zeros < i and 1 > i 12 | for(int i = 1; i <= n; ++i) { 13 | // req = ones = i 14 | int cur = pre[i] + (n-i - (pre[n] - pre[i])); 15 | ans = min(ans, cur); 16 | } 17 | return ans; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Frog Jump.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canCross(vector& stones) { 4 | int n = stones.size(); 5 | int k = n+1; 6 | set jumps[n]; 7 | jumps[0].insert(0); 8 | 9 | map pos; 10 | for(int i = 0; i < n; ++i) pos[stones[i]] = i; 11 | 12 | for(int i = 0; i < stones.size(); ++i) { 13 | for(auto &j : jumps[i]) { 14 | for(auto nxt : {j-1, j , j+1}) 15 | if(nxt>0 && pos.count(stones[i] + nxt)) 16 | jumps[ pos[ stones[i]+nxt ]].insert(nxt); 17 | } 18 | } 19 | return jumps[n-1].size() > 0; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Generate Parentheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void generate(string prefix , int l , int r , vector &res){ 4 | //cout <0) 13 | generate(prefix+"(" , l-1 , r , res); 14 | if(r>0) 15 | generate(prefix+")" , l , r-1 , res); 16 | } 17 | vector generateParenthesis(int n) { 18 | vector res; 19 | generate("" , n , n , res); 20 | return res; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Greatest Sum Divisible by Three.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxSumDivThree(vector& a) { 4 | int n = a.size(); 5 | int dp[n][3]; 6 | dp[0][0] = dp[0][1] = dp[0][2] = 0; 7 | dp[0][ a[0] % 3] = a[0]; 8 | for(int i = 1; i < n; ++i) { 9 | for(int j = 0; j < 3; ++j) { 10 | dp[i][j] = dp[i-1][j]; 11 | if( dp[i-1][(j - (a[i]%3) + 3) % 3] == 0 ) { 12 | if(dp[i][ a[i] % 3 ] == 0) 13 | dp[i][a[i] % 3] = a[i]; 14 | } else { 15 | dp[i][j] = max(dp[i-1][j ] ,a[i] + dp[i-1][(j - (a[i]%3) + 3) % 3]); 16 | } 17 | } 18 | } 19 | return max(0 , dp[n-1][0]); 20 | } 21 | }; -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Guess Number Higher or Lower II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> dp; 4 | int F(int l , int r){ 5 | if(r < l) 6 | return 0; 7 | if(dp[l][r] != -1) 8 | return dp[l][r]; 9 | if(l == r-1) 10 | return dp[l][r] = l; 11 | dp[l][r] = INT_MAX; 12 | for(int i = l+1; i < r; ++i) { 13 | dp[l][r] = min(dp[l][r] , i + max(F(l,i-1) , F(i+1, r))); 14 | } 15 | dp[l][r] = min(dp[l][r] , l + F(l+1, r)); 16 | dp[l][r] = min(dp[l][r] , r + F(l, r-1)); 17 | return dp[l][r]; 18 | } 19 | int getMoneyAmount(int n) { 20 | dp.resize(n+1, vector(n+1, -1)); 21 | for(int i = 0; i <= n; ++i) 22 | dp[i][i] = 0; 23 | return F(1 , n); 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/House Robber.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int rob(vector& nums) { 4 | int n = nums.size(); 5 | int dp[n + 1][2]; 6 | dp[0][0] = 0; // Not Robbed 0th house 7 | dp[0][1] = 0; // Robbed 0th house 8 | for(int i = 1; i <= n; ++i ) { 9 | dp[i][1] = nums[i-1] + dp[i-1][0]; 10 | dp[i][0] = max(dp[i-1][0] , dp[i-1][1]); 11 | } 12 | return max(dp[n][0] , dp[n][1]); 13 | } 14 | }; -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Integer Break.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int integerBreak(int n) { 4 | if(n < 2 ) 5 | return 0; 6 | vector dp(n+1); 7 | dp[0] = 0; 8 | dp[1] = 1; 9 | for(int i = 2 ; i <=n ; ++i) { 10 | dp[i] = 0; 11 | for(int j = 1; j< i; ++j) { 12 | dp[i] = max(dp[i] , dp[j] * dp[i-j]); 13 | dp[i] = max(dp[i] , dp[j] * (i-j)); 14 | dp[i] = max(dp[i] , j * dp[i-j] ); 15 | dp[i] = max(dp[i] , j * (i - j)); 16 | } 17 | } 18 | return dp[n]; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Integer Replacement.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int rec(long long n) { 4 | if(n == 1) 5 | return 0; 6 | if(n%2) 7 | return 1 + min( rec(n+1), rec(n-1)); 8 | return rec(n/2) + 1; 9 | } 10 | int integerReplacement(int n) { 11 | return rec(n); 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Jump Game II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int jump(vector& nums) { 4 | int n = nums.size(); 5 | if(n==1) 6 | return 0; 7 | int left = nums[0]; 8 | int mxjump = nums[0]; 9 | int jumps = 1; 10 | for(int i = 1 ; i < n-1; ++i) { 11 | mxjump = max(mxjump , nums[i]+i); 12 | --left; 13 | if(left == 0) { 14 | ++jumps; 15 | left= mxjump - i; 16 | } 17 | } 18 | return jumps; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Jump Game.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canJump(vector& nums) { 4 | int i = 0 ; 5 | int mx = 0; 6 | while(i < nums.size()) { 7 | mx = max(mx , i + nums[i]); 8 | if(i == mx) 9 | break; 10 | ++i; 11 | } 12 | return i>=nums.size()-1; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Length of Longest Fibonacci Subsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lenLongestFibSubseq(vector& a) { 4 | unordered_set s; 5 | for(auto &i : a) s.insert(i); 6 | int ans = 0, n = a.size(); 7 | for(int i =0 ; i < n; ++i) { 8 | for(int j = i +1; j < n; ++j) { 9 | int u = a[i] , v = a[j]; 10 | int len = 2; 11 | while(s.find(u+v) != s.end()){ 12 | v = v + u; 13 | u = v - u; 14 | ++len; 15 | } 16 | ans= max(ans, len); 17 | } 18 | } 19 | return ans > 2 ? ans : 0; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Longest Arithmetic Subsequence of Given Difference.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestSubsequence(vector& a, int d) { 4 | unordered_map dp; 5 | int ans = 1; 6 | for(auto &i : a) { 7 | if(dp.count(i-d)) { 8 | dp[i] = max(dp[i], 1 + dp[i-d]); 9 | ans = max(ans, dp[i]); 10 | } 11 | else 12 | dp[i] = 1; 13 | } 14 | return ans; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Longest Chunked Palindrome Decomposition.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestDecomposition(string text) { 4 | string s = ""; 5 | string t; 6 | int k = 0; 7 | int n = text.length(); 8 | for(int i = 0 ; i < n; ++i) { 9 | s+=text[i]; 10 | t = text.substr(n-1-i, s.length()); 11 | if(s == t) { 12 | ++k; 13 | s = ""; 14 | t = ""; 15 | } 16 | } 17 | return k; 18 | } 19 | }; -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Longest Common Subsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> dp; 4 | int lcs(int i , int j, string &s, string &t) { 5 | if(i < 0 || j < 0) 6 | return 0; 7 | int &ret = dp[i][j]; 8 | if(ret != -1) 9 | return ret; 10 | if(s[i] == t[j]) return ret = 1 + lcs(i-1, j-1, s, t); 11 | return ret = max( lcs(i-1, j , s, t) , lcs(i, j-1, s, t)); 12 | } 13 | int longestCommonSubsequence(string s, string t) { 14 | int n = s.length(); 15 | int m = t.length(); 16 | dp.resize(n , vector (m,-1)); 17 | int ans = lcs(n-1, m-1, s, t); 18 | return ans; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Longest Increasing Subsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lengthOfLIS(vector& nums) { 4 | if(nums.size() == 0) 5 | return 0; 6 | vector lis; 7 | lis.push_back(nums[0]); 8 | for(int i = 1; i < nums.size(); ++i) { 9 | int idx = lower_bound(lis.begin() , lis.end(), nums[i]) - lis.begin(); 10 | if(idx == lis.size()) 11 | lis.push_back(nums[i]); 12 | else 13 | lis[idx] = nums[i]; 14 | } 15 | return lis.size(); 16 | } 17 | }; -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Longest Subarray of 1's After Deleting One Element.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestSubarray(vector& a) { 4 | int n = a.size(); 5 | if(n == 1) 6 | return 0; 7 | 8 | vector l(n + 1, 0) , r(n + 1, 0); 9 | for(int i = 1; i <= n; ++i) { 10 | if(a[i-1] == 1) l[i] = 1 + l[i-1]; 11 | else l[i] = 0; 12 | } 13 | for(int i = n-1; i>=0; --i){ 14 | if(a[i] == 1) r[i] = 1 + r[i+1]; 15 | else r[i] = 0; 16 | } 17 | int ans = max( r[1] , l[n-1] ); 18 | for(int i = 1; i < n-1; ++i) { 19 | ans = max(ans, l[i] + r[i+1]); 20 | } 21 | return ans; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Longest Turbulent Subarray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxTurbulenceSize(vector& a) { 4 | int n = a.size(); 5 | vector< int > dp[2]; // dp[0][i] // prev element was smaller , dp[0][1] => prev element was larger 6 | 7 | dp[0].resize(n , 1); 8 | dp[1] = dp[0]; 9 | int ans = 1; 10 | for(int i = 1; i < n; ++i) { 11 | if(a[i] > a[i-1]) 12 | dp[0][i] = 1 + dp[1][i-1]; 13 | if(a[i] < a[i-1]) 14 | dp[1][i] = 1 + dp[0][i-1]; 15 | ans = max(ans, max(dp[0][i] , dp[1][i])); 16 | } 17 | return ans; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Maximum Absolute Sum of Any Subarray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int kadane(vector &a){ 4 | int n = a.size(); 5 | int csum = 0, msum = 0; 6 | for(auto &i : a) { 7 | msum = max(msum , csum); 8 | if(csum + i < 0) { 9 | csum = 0; 10 | } else csum += i; 11 | } 12 | msum = max(msum , csum); 13 | return msum; 14 | } 15 | int maxAbsoluteSum(vector& nums) { 16 | int ans = kadane(nums); 17 | for(auto &i : nums) i = -i; 18 | ans = max(ans, kadane(nums)); 19 | return ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Maximum Alternating Subsequence Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long maxAlternatingSum(vector& nums) { 4 | // variation of stock selling problem 5 | int64_t oddMax = nums[0] , evenMax = 0; 6 | for(int i = 1; i < nums.size(); ++i) { 7 | int64_t newEven = max(evenMax , oddMax - nums[i]); // sell 8 | int64_t newOdd = max(oddMax , evenMax + nums[i]); 9 | evenMax = newEven; 10 | oddMax = newOdd; 11 | } 12 | return oddMax; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Maximum Length of Pair Chain.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findLongestChain(vector>& a) { 4 | //sort by ending 5 | sort(a.begin(), a.end(), [](vectorp, vector q) -> bool { 6 | if(p[1] == q[1]) 7 | return p[0] < q[0]; 8 | return p[1] < q[1]; 9 | }); 10 | int n = a.size(); 11 | vector dp(n, 1); 12 | int ans = 1; 13 | for(int i = 1; i < n; ++i) { 14 | for(int j = i-1; j >= 0; --j) { 15 | if(a[i][0] > a[j][1]) 16 | dp[i] = max(dp[i], 1 + dp[j]); 17 | } 18 | ans = max(ans , dp[i]); 19 | } 20 | return ans; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Maximum Length of Repeated Subarray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findLength(vector& A, vector& B) { 4 | vector> dp(A.size() , vector (B.size() , 0 )); 5 | for(int i = 0 ; i < A.size(); ++i) 6 | for(int j = 0 ; j < B.size(); ++j) 7 | if(A[i] == B[j] ) dp[i][j] = 1; 8 | for(int i = 0 ; i < A.size(); ++i) { 9 | for(int j = 0; j < B.size(); ++j) { 10 | if( i>0 && j >0 && dp[i][j]>0) 11 | dp[i][j]+=dp[i-1][j-1]; 12 | } 13 | } 14 | int ans = 0; 15 | for(int i = 0 ; i < A.size(); ++i) 16 | ans = max(ans , *max_element(dp[i].begin() , dp[i].end())); 17 | return ans; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Maximum Length of Subarray With Positive Product.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int getMaxLen(vector& nums) { 4 | int ans = 0; 5 | int p = -1 , n = INT_MAX; 6 | int prod = 1; 7 | for(int i = 0; i < nums.size(); ++i) { 8 | if(nums[i] == 0) { 9 | p = i; 10 | n = INT_MAX; 11 | prod = 1; 12 | continue; 13 | } 14 | nums[i]/= abs(nums[i]); 15 | prod *= nums[i]; 16 | if(prod > 0) 17 | ans =max(ans, i - p); 18 | else { 19 | n = min(n , i); 20 | ans = max(ans, i-n); 21 | } 22 | } 23 | return ans; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Maximum Product Subarray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProduct(vector& nums) { 4 | long long int prod = INT_MIN; 5 | long long int sofar = 1; 6 | vector dp(nums.size() , 1); 7 | int prev = -1; 8 | for(int i = 0 ; i < nums.size(); ++i) { 9 | sofar*= nums[i]; 10 | if(sofar < 0) { 11 | if(prev == -1) { 12 | prev = i; 13 | }else { 14 | prod = max(prod , sofar/dp[prev] ); 15 | } 16 | } 17 | dp[i] = sofar; 18 | prod = max( prod , sofar); 19 | if(sofar == 0) { 20 | sofar = 1; 21 | prev = -1; 22 | } 23 | } 24 | return prod; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Maximum Score from Performing Multiplication Operations.cpp: -------------------------------------------------------------------------------- 1 | const int INF = 2e9; 2 | class Solution { 3 | public: 4 | vector> dp; 5 | inline int rec(int idx, int l, int r, vector &a, vector &b) { 6 | if(idx == b.size()) return 0; 7 | if(dp[l][r] != -INF) return dp[l][r]; 8 | return dp[l][r] = max( 9 | a[l]*b[idx] + rec(idx+1, l+1, r, a, b), 10 | a[a.size()-1-r]*b[idx] + rec(idx+1, l, r+1, a, b) ); 11 | } 12 | int maximumScore(vector& a, vector& b) { 13 | dp.resize(b.size() , vector (b.size(), -INF)); 14 | return rec(0, 0, 0, a, b); 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Maximum Subarray Sum with One Deletion.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maximumSum(vector& a) { 4 | int n = a.size(); 5 | vector pre(n), suf(n); 6 | pre[0] = a[0]; 7 | for(int i = 1; i < n; ++i) pre[i] = max(a[i], a[i] + pre[i-1]); 8 | suf[n-1] = a[n-1]; 9 | for(int i = n-2; i >= 0; --i) suf[i] = max(a[i], a[i] + suf[i+1]); 10 | int ans = a[0]; 11 | for(int i = 0; i < n; ++i) { 12 | ans = max(ans, max(pre[i], suf[i])); 13 | // delete ith element 14 | if(i > 0 || i < n-1) 15 | ans = max(ans, (i>0 ? pre[i-1] : 0) + (i < n-1 ? suf[i+1] : 0)); 16 | } 17 | return ans; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Maximum Subarray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxSubArray(vector& nums) { 4 | // O(n) solution 5 | int ans = nums[0] , cs = nums[0]; 6 | for(int i = 1; i < nums.size(); ++i) { 7 | if(cs < 0) 8 | cs = 0; 9 | cs+= nums[i]; 10 | ans = max(ans , cs); 11 | } 12 | return ans; 13 | 14 | // Divide and Conquer 15 | // Can be done by storing prefix , suffix , sum at each node and merging 16 | // same as we do in seg tree 17 | } 18 | }; -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Min Cost Climbing Stairs.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minCostClimbingStairs(vector& cost) { 4 | int n = cost.size(); 5 | int dp[n + 1]; 6 | dp[0] = 0; 7 | dp[1] = 0; 8 | for(int i = 2; i <= n; ++i) { 9 | dp[i] = min(dp[i-1] + cost[i-1] , dp[i-2] + cost[i-2]); 10 | } 11 | return dp[n]; 12 | } 13 | }; -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Minimize the Difference Between Target and Chosen Elements.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minimizeTheDifference(vector>& mat, int target) { 4 | const int NAX= 70 * 70 + 1; 5 | bitset sum; 6 | bitset newsum; 7 | sum[0] = 1; 8 | 9 | for(auto &i : mat) { 10 | newsum = 0; 11 | for(auto &j : i) { 12 | newsum |= sum << j; 13 | } 14 | sum = newsum; 15 | } 16 | 17 | int ans = INT_MAX; 18 | for(int i = 0; i < NAX; ++i) 19 | if(sum[i]) ans = min(ans, abs(i - target)); 20 | return ans; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Minimum Cost Tree From Leaf Values.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int mctFromLeafValues(vector& arr) { 4 | if(arr.size() == 1) 5 | return 0; 6 | int minP = INT_MAX; 7 | int ind = -1; 8 | for(int i = 1 ; i < arr.size(); ++i) { 9 | if((arr[i]* arr[i-1]) <= minP) { 10 | minP = arr[i] * arr[i-1]; 11 | ind = i-1; 12 | } 13 | } 14 | cout << ind << " " << minP << endl; 15 | vector a(arr.size()-1); 16 | for(int i = 0 ; i <= ind; ++i) 17 | a[i] = arr[i]; 18 | for(int i = ind+2; i< arr.size(); ++i) 19 | a[i - 1] = arr[i]; 20 | a[ind] = max(arr[ind] , arr[ind+1]); 21 | return minP + mctFromLeafValues(a); 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Minimum Deletion Cost to Avoid Repeating Letters.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minCost(string s, vector& cost) { 4 | int res = 0; 5 | int i = 0, n = s.length(); 6 | while( i < n ) { 7 | int j = i+1 , mc = cost[i], tc = cost[i]; 8 | while(s[j] == s[i]) { 9 | mc = max(mc, cost[j]); 10 | tc += cost[j]; 11 | ++j; 12 | } 13 | res += tc - mc; 14 | i = j; 15 | } 16 | return res; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Minimum Deletions to Make String Balanced.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minimumDeletions(string s) { 4 | // same as 01 problem 5 | int n = s.length(); 6 | int c[2] = {0}; 7 | int pre[n+1]; 8 | pre[0] = 0; 9 | for(int i = 1; i <= n; ++i) { 10 | pre[i] = pre[i-1] + (s[i-1] - 'a'); 11 | c[s[i-1]-'a']++; 12 | } 13 | 14 | int ans = c[0];// all bs 15 | // all a = i 16 | for(int i = 1; i <= n; ++i) { 17 | // cur = cnt b < i + cnt a >= i 18 | int cur = pre[i] + (n-i - pre[n] + pre[i]); 19 | ans = min(ans, cur); 20 | } 21 | return ans; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Minimum Falling Path Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minFallingPathSum(vector>& A) { 4 | int n = A.size(); 5 | if(!n) return 0; 6 | for(int i = n-2; i>=0; --i) 7 | for(int j = 0; j =0 && k& a) { 6 | int ans = 0; 7 | int cur = 0; 8 | for(auto &i : a ) { 9 | ans += ( i > cur ? i - cur : 0); 10 | cur = i; 11 | } 12 | return ans; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Minimum One Bit Operations to Make Integers Zero.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minimumOneBitOperations(int n) { 4 | // 2 : 10 -> 11 -> 01 -> 00 5 | // 4 : 100 -> 101 -> 111 -> 110 -> 010-> 011 -> 001 -> 000 6 | // For 2^n ans = 2^(n+1) - 1 7 | // dp[n] = moves to make this number from 0 8 | // dp[n] = moves to make 111111 - moves to make (number after removing last bit) 9 | if(n == 0) 10 | return 0; 11 | int l = log2(n); 12 | return (1<<(l + 1)) - 1 - minimumOneBitOperations(n - (1<>& grid) { 5 | int rows = grid.size(); 6 | if(rows == 0) 7 | return 0; 8 | int cols = grid[0].size(); 9 | if(cols == 0) 10 | return 0; 11 | for(int c = 1; c < cols; ++c) 12 | grid[0][c]+=grid[0][c-1]; 13 | for(int r = 1; r < rows; ++r) 14 | grid[r][0]+= grid[r-1][0]; 15 | for(int r = 1 ; r < rows; ++r) 16 | for(int c = 1; c < cols; ++c) 17 | grid[r][c]+= min(grid[r-1][c] , grid[r][c-1]); 18 | return grid[rows-1][cols-1]; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Minimum Score Triangulation of Polygon.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minScoreTriangulation(vector& A) { 4 | int n=A.size(); 5 | vector> dp(n,vector(n,INT_MAX));//dp[startId][endId] 6 | //base of dp 7 | for (int i=0; i& o) { 5 | int n = o.size(); 6 | vector< vector> dp(n+1, vector(3, INF)); 7 | dp[0][1] = 0; 8 | dp[0][0] = 1; 9 | dp[0][2] = 1; 10 | for(int i = 1; i <= n; ++i) { 11 | for(int j = 0; j < 3; ++j) { 12 | if(o[i-1] != j+1) 13 | dp[i][j] = dp[i-1][j]; 14 | } 15 | for(int j = 0; j < 3; ++j) { 16 | if(o[i-1] != j+1) 17 | for(int k = 0; k < 3; ++k) 18 | dp[i][j] = min(dp[i][j], 1 + dp[i][k]); 19 | } 20 | } 21 | return min(dp[n][0] , min(dp[n][1] , dp[n][2])); 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/N-th Tribonacci Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int tribonacci(int n) { 4 | int tri[n+3]; 5 | tri[0] = 0; 6 | tri[1] = tri[2] = 1; 7 | for(int i = 3; i <= n; ++i) tri[i] = tri[i-1] + tri[i-2] + tri[i-3]; 8 | return tri[n]; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Non-overlapping Intervals.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int eraseOverlapIntervals(vector>& a) { 4 | sort(a.begin() , a.end(), [](vector &u, vector&v) { 5 | if(u[1] == v[1]) 6 | return u[0] < v[0]; 7 | return u[1] < v[1]; 8 | }); 9 | int n = a.size(); 10 | int ans = 0; 11 | int en = a[0][1]; 12 | for(int i = 1; i < n; ++i) { 13 | if( en > a[i][0] ) 14 | ++ans; 15 | else { 16 | en = max(en , a[i][1]); 17 | } 18 | } 19 | return ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Number of Dice Rolls With Target Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int ways(int d , int f , int target , vector> &dp) { 4 | const int MOD = 1e9 + 7; 5 | if(d == 0 ) 6 | return target == 0; 7 | if(dp[target][d]!=-1) 8 | return dp[target][d]; 9 | int w = 0; 10 | for(int i = 1 ; i <= min(f , target); ++i) 11 | w = (w + ways(d-1 , f , target - i , dp)) % MOD; 12 | dp[target][d] = w%MOD; 13 | return dp[target][d]; 14 | } 15 | int numRollsToTarget(int d, int f, int target) { 16 | if(target < d) 17 | return 0; 18 | vector> dp( target+1 , vector (d+1 , -1)); 19 | return ways(d , f , target , dp); 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Number of Smooth Descent Periods of a Stock.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long getDescentPeriods(vector& prices) { 4 | long long ans = 0, tmp; 5 | int i = 0, n = prices.size(); 6 | while(i < n) { 7 | int j = i+1; 8 | while(j < n && prices[j]+1 == prices[j-1]) 9 | ++j; 10 | tmp = j-i; 11 | ans += (tmp*(tmp+1))/2; 12 | i = j; 13 | } 14 | return ans; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Number of Sub-arrays With Odd Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numOfSubarrays(vector& arr) { 4 | int cnt[2] = {0}; 5 | cnt[0] = 1; 6 | int ans = 0; 7 | const int mod = 1e9 + 7; 8 | int pre = 0; 9 | for(auto &i : arr) { 10 | pre ^= (i&1); 11 | ans = (ans + cnt[1-pre]) % mod; 12 | cnt[pre]++; 13 | } 14 | return ans; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Number of Ways to Stay in the Same Place After Some Steps.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | int numWays(int steps, int n) { 5 | vector< long long int > cur(n , 0); 6 | vector< long long int > prev(n , 0); 7 | prev[0] = 1; 8 | const int MOD = 1e9 + 7; 9 | for(int step = 0; step < steps; ++step) { 10 | for(int pos = 0; pos <= min(step+1,n-1); ++pos) { 11 | cur[pos] = (pos > 0 ? prev[pos-1] : 0) + prev[pos] + (pos+1< n ? prev[pos + 1] : 0); 12 | cur[pos] %= MOD; 13 | } 14 | for(int i = 0 ; i <= min(steps+1,n-1); ++i) 15 | prev[i] = cur[i]; 16 | } 17 | return (int)prev[0]; 18 | } 19 | }; -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Optimal Division.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | /* 4 | To increase the value of p/q we can 5 | 1.increase p( we can't) 6 | 2.decrese q ( to do this we do not put brackets in q and solve it first) since p/q/r <= p/(q/r) 7 | */ 8 | string optimalDivision(vector& nums) { 9 | if( nums.size() == 1) 10 | return to_string(nums[0]); 11 | if( nums.size() == 2) 12 | return to_string(nums[0]) + "/" + to_string(nums[1]); 13 | 14 | string res = ""; 15 | res += to_string(nums[0]) + "/("; 16 | for(int i = 1; i < nums.size()-1; ++i) { 17 | res += to_string(nums[i]) + "/"; 18 | } 19 | res += to_string(nums.back()) + ")"; 20 | 21 | return res; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Partition Equal Subset Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canPartition(vector& a) { 4 | int sum = accumulate(a.begin(), a.end(), 0); 5 | if( sum & 1 ) 6 | return false; 7 | // using bitsets 8 | bitset< 200*100 + 1 > b; 9 | b[0] = 1; 10 | for(auto &i : a) 11 | b |= b << i; 12 | return b[sum/2]; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Pascal's Triangle II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector getRow(int rowIndex) { 4 | vector prev; 5 | prev.push_back(1); 6 | if(rowIndex == 0) 7 | return prev; 8 | for(int i = 1; i <= rowIndex; ++i) { 9 | vector cur(i+1); 10 | cur[0] = 1; 11 | cur[i] = 1; 12 | for(int j = 1; j < i; ++j ) 13 | cur[j] = prev[j-1] + prev[j]; 14 | prev = cur; 15 | } 16 | return prev; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Pascal's Triangle.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> generate(int numRows) { 4 | vector> p; 5 | if(numRows == 0) 6 | return p; 7 | vector curr; 8 | curr.push_back(1); 9 | p.push_back(curr); 10 | for(int i = 2; i<=numRows; ++i) { 11 | curr.push_back(1); 12 | curr[0] = 1; 13 | for(int j = 1; j dp(n+1 , n+1); 7 | dp[0] = 0; 8 | for(int i = 1; i*i <= n; ++i) { 9 | for(int j = i*i ; j<=n; ++j) 10 | dp[j] = min( dp[j-i*i] + 1 , dp[j]); 11 | } 12 | return dp[n]; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Range Sum Query - Immutable.cpp: -------------------------------------------------------------------------------- 1 | class NumArray { 2 | public: 3 | vector< int > pre; 4 | NumArray(vector& nums) { 5 | pre.resize(nums.size() + 1 , 0); 6 | for(int i = 0; i < nums.size(); ++i) 7 | pre[i + 1] = pre[i] + nums[i]; 8 | } 9 | 10 | int sumRange(int i, int j) { 11 | return pre[j + 1] - pre[i]; 12 | } 13 | }; 14 | 15 | /** 16 | * Your NumArray object will be instantiated and called as such: 17 | * NumArray* obj = new NumArray(nums); 18 | * int param_1 = obj->sumRange(i,j); 19 | */ -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Rotate Function.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxRotateFunction(vector& a) { 4 | // 0a0 + 1a1 + 2a2 + 3a3 + .. . . + an-2 + an-1 5 | //want// 0an-1 1a0 2a1 3a2 n-1an-2 6 | // have nan-1 extra 7 | int n = a.size(); 8 | int ans; 9 | int cur = 0; 10 | int sum = accumulate(a.begin() , a.end(), 0); 11 | for(int i = 0 ; i < n; ++i) 12 | cur += i * a[i]; 13 | ans = cur; 14 | for(int i = 1; i < n; ++i) { 15 | ans = max(cur, ans); 16 | cur += sum; 17 | cur -= n * a[n-i]; 18 | } 19 | ans = max(ans, cur); 20 | return ans; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Rotated Digits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int valid(int N) { 4 | if(N==0) return false; 5 | set s; 6 | while(N!=0) { 7 | int r = N%10; 8 | s.insert(r); 9 | N/=10; 10 | } 11 | if(s.find(3)!=s.end() || s.find(4)!=s.end() || s.find(7)!=s.end()) 12 | return false; 13 | return s.find(2)!=s.end() || s.find(5)!=s.end() || s.find(6)!=s.end() || s.find(9)!=s.end(); 14 | } 15 | int rotatedDigits(int N) { 16 | int c = 0; 17 | for(int i = 1 ; i <= N; ++i) { 18 | c+= valid(i); 19 | } 20 | return c; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Sort Integers by The Power Value.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | unordered_map m; 4 | int p(int n) { 5 | if(m.count(n)) 6 | return m[n]; 7 | if(n % 2 == 0) 8 | return m[n] = 1 + p(n/2); 9 | return m[n] = 1 + p(3*n + 1); 10 | } 11 | int getKth(int lo, int hi, int k) { 12 | vector> a; 13 | m[1] = 0; 14 | for(int i = lo; i <= hi; ++i ) { 15 | a.push_back({p(i) , i}); 16 | } 17 | sort(a.begin() , a.end()); 18 | return a[k-1].second; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Stone Game IV.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool win(int n , vector< int > &dp) { 4 | if(dp[n] != -1) 5 | return dp[n]; 6 | for(int i = 1; i * i <= n; ++i) 7 | if(win(n - i*i , dp) == false) 8 | return dp[n] = true; 9 | return dp[n] = false; 10 | } 11 | bool winnerSquareGame(int n) { 12 | vector< int > dp(n + 1 , -1); 13 | dp[1] = 1; 14 | return win(n , dp); 15 | } 16 | }; -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Stone Game.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int win(int i , int j , vector &piles, vector> &dp) { 4 | if(j < i) 5 | return 0; 6 | if(dp[i][j] != -1) 7 | return dp[i][j]; 8 | if((j-i)%2 == 1) { 9 | dp[i][j] = max(piles[i] + win(i+1 , j , piles , dp) , piles[j] + win(i , j-1 , piles , dp)); 10 | } else { 11 | dp[i][j] = max(win(i+1 , j , piles , dp)-piles[i] , win(i , j-1 , piles , dp) - piles[j]); 12 | } 13 | return dp[i][j]; 14 | } 15 | bool stoneGame(vector& piles) { 16 | int a = piles.size(); 17 | vector< vector > dp(a+1, vector (a+1 , -1)); 18 | return win(0 , piles.size()-1, piles , dp) > 0; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Super Ugly Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int nthSuperUglyNumber(int n, vector& p) { 4 | vector ugly(1, 1); 5 | int m = p.size(); 6 | vector ptr( m , 0); 7 | for(int u = 1; u < n; ++u) { 8 | vector newugly(m, 0); 9 | int mn = INT_MAX; 10 | for(int i = 0 ; i < m; ++i) { 11 | newugly[i] = ugly[ptr[i]] * p[i]; 12 | if(newugly[i] > ugly.back()) 13 | mn = min(mn , newugly[i]); 14 | } 15 | ugly.push_back(mn); 16 | for(int i = 0 ; i < m; ++i) 17 | if(newugly[i] == mn) 18 | ++ptr[i]; 19 | } 20 | // for(auto &i : ugly) cout << i << " "; 21 | return ugly[n-1]; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Tallest Billboard.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | const int INF = 1e7; 4 | vector> dp; 5 | int rec(int i, int diff, vector &r) { 6 | if(i < 0) return diff == 0 ? 0 : -INF; 7 | if(dp[i][diff] != -1) return dp[i][diff]; 8 | int &ret = dp[i][diff]; 9 | ret = rec(i-1, diff, r); 10 | ret = max(ret, r[i] + rec(i-1, diff + r[i] , r)); 11 | ret = max(ret, r[i] + rec(i-1, abs(diff - r[i]), r)); 12 | return ret; 13 | } 14 | int tallestBillboard(vector& rods) { 15 | int n = rods.size(); 16 | dp.resize(n, vector (5001, -1)); 17 | int ans = rec(n-1, 0, rods); 18 | return ans/2; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Target Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int ways(int i ,long long int S , vector &nums) { 4 | if(i==0) { 5 | return S==0; 6 | } 7 | return ways(i-1 , S-nums[i-1] , nums) + ways(i-1 , S+nums[i-1] , nums); 8 | } 9 | int findTargetSumWays(vector& nums, int S) { 10 | return ways(nums.size() , S , nums); 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Trapping Rain Water.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int trap(vector& height) { 4 | if(height.size()==0) 5 | return 0; 6 | int n = height.size(); 7 | int lbig[n] , rbig[n]; 8 | rbig[n-1] = height[n-1]; 9 | for(int i = n-2; i>=0; --i) { 10 | rbig[i] = max(height[i] , rbig[i+1]); 11 | } 12 | lbig[0] = height[0]; 13 | for(int i = 1; i < n; ++i) { 14 | lbig[i] = max(lbig[i-1] , height[i]); 15 | } 16 | int ans = 0; 17 | for(int i = 0 ; i < n;++i) { 18 | ans+= min(lbig[i] , rbig[i]) - height[i]; 19 | } 20 | return ans; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Triangle.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minimumTotal(vector>& triangle) { 4 | for(int i = triangle.size()-2; i>=0; --i) { 5 | for(int j = 0; j <=i ;++j) 6 | triangle[i][j]+= min(triangle[i+1][j] , triangle[i+1][j+1]); 7 | } 8 | return triangle[0][0]; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Triples With Bitwise And Equal to Zero.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countTriplets(vector& a) { 4 | const int MXN = 1 << 16; 5 | int n = a.size(); 6 | vector< int > dp(MXN , 0); 7 | for(int i = 0 ; i < n; ++i){ 8 | for(int j = 0; j> dp; 4 | int lcs(int i , int j, vector &a, vector &b) { 5 | if(i < 0 || j < 0) 6 | return 0; 7 | int &ret = dp[i][j]; 8 | if(ret != -1) 9 | return ret; 10 | if(a[i] == b[j]) return ret = 1 + lcs(i-1, j-1, a, b); 11 | return ret = max(lcs(i-1, j, a, b), lcs(i, j-1, a, b)); 12 | } 13 | //ans is LCS of vectors 14 | int maxUncrossedLines(vector& a, vector& b) { 15 | int n = a.size(); 16 | int m = b.size(); 17 | dp.resize(n , vector (m, -1)); 18 | int ans =lcs(n-1, m-1, a, b); 19 | return ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Unique Binary Search Trees.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numTrees(int n) { 4 | vector catalan(n+1 , 0); 5 | catalan[0] = 1; 6 | for(int i = 1 ; i <= n; ++i) { 7 | for(int j = 1; j <=i; ++j) { 8 | catalan[i]+= catalan[j-1] * catalan[i-j]; 9 | } 10 | } 11 | return catalan[n]; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Unique Paths.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int uniquePaths(int m, int n) { 4 | double paths = 1; 5 | for(int i = n; i < m+n-1; ++i) { 6 | paths*= i; 7 | paths/= (i - (n-1)); 8 | } 9 | return ceil(paths); 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Video Stitching.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int videoStitching(vector>& clips, int T) { 4 | int s = 0; 5 | int cnt = 0; 6 | while( true ) { 7 | int e = -1; 8 | for(auto &i : clips) 9 | if(i[0] <= s && i[1] > s) 10 | e = max( e , i[1]); 11 | ++cnt; 12 | if(e >= T) { 13 | return cnt; 14 | } 15 | s = e; 16 | if(e == -1) 17 | return -1; 18 | } 19 | return -1; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Vowels of All Substrings.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long countVowels(string word) { 4 | long long ans =0; 5 | for(int i = 0; i < word.size(); ++i) 6 | if(word[i] == 'a' || word[i] == 'e' || word[i] == 'i' || word[i] == 'o' || word[i] == 'u') 7 | ans += (long long)(i+1) * (long long)(word.size()-i); 8 | return ans; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Where Will the Ball Fall.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findBall(vector>& g) { 4 | int n = g.size(); 5 | int m = g[0].size(); 6 | 7 | vector> dp(n+1 , vector (m , -1)); 8 | if(m == 1) return dp[0]; 9 | 10 | for(int i = 0; i < m; ++i) 11 | dp[n][i] = i; 12 | 13 | for(int r = n-1; r >= 0; --r) { 14 | for(int i = 0; i < m; ++i) { 15 | if(g[r][i] == 1) { 16 | if(i < m-1 && g[r][i+1] != -1) dp[r][i] = dp[r+1][i+1]; 17 | } else { 18 | if(i > 0 && g[r][i-1] != 1) dp[r][i] = dp[r+1][i-1]; 19 | } 20 | } 21 | } 22 | 23 | return dp[0]; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/Wiggle Subsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int wiggleMaxLength(vector& a) { 4 | int n = a.size(); 5 | vector dp[2]; 6 | dp[0].resize(n , 1); 7 | dp[1] = dp[0]; 8 | int ans = 1; 9 | for(int i = 1; i < n; ++i) { 10 | for(int j = 0; j < i; ++j) { 11 | if(a[i] > a[j]) 12 | dp[0][i] = max(dp[0][i] , 1 + dp[1][j]); 13 | if(a[i] < a[j]) 14 | dp[1][i] = max(dp[1][i] , 1 + dp[0][j]); 15 | } 16 | ans = max(ans, max(dp[0][i], dp[1][i])); 17 | } 18 | return ans; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Dynamic Programming/LeetCode/readme.txt: -------------------------------------------------------------------------------- 1 | LeetCode Dynamic Programming Solutions 2 | Solved: 213/329 3 | -------------------------------------------------------------------------------- /Dynamic Programming/MashupGalenColin/readme.txt: -------------------------------------------------------------------------------- 1 | Mashup link: https://codeforces.com/contests/302977 2 | -------------------------------------------------------------------------------- /FFT/readme.txt: -------------------------------------------------------------------------------- 1 | FFT Standard Problems 2 | -------------------------------------------------------------------------------- /Hiring Round Problems/readme.md: -------------------------------------------------------------------------------- 1 | Problems & Solutions from hiring rounds. 2 | -------------------------------------------------------------------------------- /Interview Prep/Google/AfterAcademy/12. Move zeroes to an end.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @type of arr: integer array 3 | * @return type: integer array 4 | */ 5 | class Solution { 6 | public: 7 | vector moveZeroes(vector& arr) { 8 | // write your awesome code here 9 | int j = -1; 10 | for(int i = 0; i < arr.size(); ++i) { 11 | if(arr[i] != 0) { 12 | ++j; 13 | swap(arr[i], arr[j]); 14 | } 15 | } 16 | return arr; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Interview Prep/Google/AfterAcademy/13. Merge two sorted arrays.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @type of arr1: integer array(sorted) 3 | * @type of arr2: integer array(sorted) 4 | * @return type: integer array 5 | */ 6 | class Solution { 7 | public: 8 | vector mergeSortedArray(vector& arr1, vector& arr2) { 9 | // write your awesome code here 10 | vector c; 11 | int i = 0, j=0, n = arr1.size(), m = arr2.size(); 12 | while(i < n && j < m) { 13 | if(arr1[i] <=arr2[j]) { 14 | c.push_back(arr1[i++]); 15 | } else { 16 | c.push_back(arr2[j++]); 17 | } 18 | } 19 | while(i < arr1.size()) c.push_back(arr1[i++]); 20 | while(j < arr2.size()) c.push_back(arr2[j++]); 21 | return c; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Interview Prep/Google/AfterAcademy/14. Container with Most Water.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @type of arr: integer array 3 | * @return type: integer 4 | */ 5 | class Solution { 6 | public: 7 | int mostWater(vector& arr) { 8 | // write your awesome code here 9 | int n = arr.size(); 10 | int i = 0, j = n-1; 11 | int ans = 0; 12 | while( i < j ) { 13 | ans = max(ans, (j-i) * min(arr[j],arr[i])); 14 | if(arr[i] > arr[j]) --j; 15 | else ++i; 16 | } 17 | return ans; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Interview Prep/Google/AfterAcademy/15. Remove duplicates from sorted array.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @type of arr: integer array 3 | * @return type: integer 4 | */ 5 | class Solution { 6 | public: 7 | int removeDuplicates(vector& arr) { 8 | // write your awesome code here 9 | unordered_set seen; 10 | int j = -1, n = arr.size(); 11 | for(int i = 0; i < n; ++i) { 12 | if(seen.find(arr[i]) == seen.end()) { 13 | seen.insert(arr[i]); 14 | swap(arr[i], arr[++j]); 15 | } 16 | } 17 | return j+1; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Interview Prep/Google/AfterAcademy/17. Find minimum element in sorted and rotated array.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @type of arr: integer array 3 | * @return type: integer 4 | */ 5 | class Solution { 6 | public: 7 | int findMinElement(vector& arr) { 8 | // write your awesome code here 9 | int n = arr.size(); 10 | if(n == 1) { 11 | return arr[0]; 12 | } 13 | // find mountain peak 14 | int lo = 0, hi = n-2; 15 | while(lo <= hi) { 16 | int mid = lo + ((hi-lo)>>1); 17 | if(arr[mid] >= arr[0]) lo = mid + 1; 18 | else hi = mid - 1; 19 | } 20 | // peak = lo-1 21 | return arr[lo]; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Interview Prep/Google/AfterAcademy/2. Reverse Bits.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @type of num: unsigned integer 3 | * @return type: unsigned integer 4 | */ 5 | class Solution { 6 | public: 7 | unsigned int reverseBits(unsigned int num) { 8 | // write your awesome code here 9 | int lg = log2(num); 10 | unsigned int ans = 0; 11 | for(int i = 0; i <= lg; ++i) { 12 | if(num & (1< searchRange(vector& arr, int target) { 9 | // write your awesome code here 10 | int idx1 = lower_bound(arr.begin(), arr.end(), target)-arr.begin(); 11 | int idx2 = upper_bound(arr.begin(), arr.end(), target)-arr.begin()-1; 12 | 13 | if(idx1==arr.size() || arr[idx1] != target || idx2 == -1 || arr[idx2]!=target) 14 | return {-1,-1}; 15 | return {idx1, idx2}; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Interview Prep/Google/AfterAcademy/21. Longest Common Prefix.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @type of arr: array of strings 3 | * @return type: string 4 | */ 5 | class Solution { 6 | public: 7 | string longestCommonPrefix(vector& arr) { 8 | // write your awesome code here 9 | string pref = ""; 10 | int minLen = INT_MAX; 11 | for(auto &s : arr) minLen = min(minLen, (int)s.length()); 12 | for(int i = 0; i < minLen; ++i) { 13 | bool f = true; 14 | for(int j = 1; j < arr.size(); ++j) 15 | if(arr[j][i] != arr[0][i]) { 16 | f = 0; 17 | break; 18 | } 19 | if(!f) break; 20 | pref += arr[0][i]; 21 | } 22 | return pref; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Interview Prep/Google/AfterAcademy/23. Swap List Nodes in pairs.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 | 10 | /** 11 | * @type of head: ListNode 12 | * @return type: ListNode 13 | */ 14 | class Solution { 15 | public: 16 | ListNode* swapPairs(ListNode* head) { 17 | // write your awesome code here 18 | if(!head || !head->next) return head; 19 | ListNode* temp = swapPairs(head->next->next); 20 | ListNode* nxt = head->next; 21 | nxt->next = head; 22 | head->next = temp; 23 | return head = nxt; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Interview Prep/Google/AfterAcademy/3. Square Root of Integer.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @type of num: integer 3 | * @return type: integer 4 | */ 5 | class Solution { 6 | public: 7 | int intSqrt(int num) { 8 | // write your awesome code here 9 | int lo = 0, hi = num; 10 | while(lo <= hi) { 11 | int mid = lo + ((hi-lo)>>1); 12 | if((num/mid) >= mid) { 13 | lo = mid + 1; 14 | } else { 15 | hi = mid - 1; 16 | } 17 | } 18 | return lo-1; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Interview Prep/Google/AfterAcademy/31. Find next greater element in an array.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @type of arr: integer array 3 | * @return type: integer array 4 | */ 5 | class Solution { 6 | public: 7 | vector findNextGreater(vector& arr) { 8 | // write your awesome code here 9 | int n = arr.size(); 10 | stack st; 11 | vector RGE(n, -1); 12 | for(int i = 0; i < n; ++i) { 13 | if(st.empty() || arr[st.top()] >= arr[i]) 14 | st.push(i); 15 | else { 16 | while(!st.empty() && arr[st.top()] < arr[i]) { 17 | RGE[st.top()] = arr[i]; 18 | st.pop(); 19 | } 20 | st.push(i); 21 | } 22 | } 23 | return RGE; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Interview Prep/Google/AfterAcademy/32. Trapping rain water.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @type of arr: integer array 3 | * @return type: integer 4 | */ 5 | class Solution { 6 | public: 7 | int maxWaterTrapped(vector& arr) { 8 | // write your awesome code here 9 | int n = arr.size(); 10 | vector rmax(n, 0); 11 | rmax[n-1] = arr[n-1]; 12 | for(int i = n-2; i >= 0; --i) 13 | rmax[i] = max(rmax[i+1], arr[i]); 14 | int lmax = arr[0]; 15 | int water = 0; 16 | for(int i = 1; i < n-1; ++i) { 17 | int cwater = min(lmax, rmax[i+1]) - arr[i]; 18 | water += max(0, cwater); 19 | lmax = max(lmax, arr[i]); 20 | } 21 | return water; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Interview Prep/Google/AfterAcademy/35. Check for balanced parentheses in an expression.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @type of s: string 3 | * @return type: integer 4 | */ 5 | class Solution { 6 | public: 7 | int checkParentheses(string s) { 8 | // write your awesome code here 9 | stack Stack; 10 | for(char c: s) { 11 | if(c == '(' || c == '[' || c == '{') Stack.push(c); 12 | else { 13 | if(( c==')' && Stack.top()=='(' ) || 14 | ( c==']' && Stack.top()=='[' ) || 15 | ( c=='}' && Stack.top()=='{' )) Stack.pop(); 16 | else return 0; 17 | } 18 | } 19 | return Stack.size() == 0; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Interview Prep/Google/AfterAcademy/4. Calculate power function.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @type of k: integer 3 | * @type of n: unsigned integer 4 | * @return type: integer 5 | */ 6 | class Solution { 7 | public: 8 | int fpow(int k,unsigned int n) { 9 | if(n == 0) return 1; 10 | int x = fpow(k, n/2); 11 | x *= x; 12 | if(n&1) x *= k; 13 | return x; 14 | } 15 | int calculatePower(int k, unsigned int n) { 16 | // write your awesome code here 17 | return fpow(k, n); 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Interview Prep/Google/AfterAcademy/40. Path sum in binary tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode* left; 6 | * TreeNode* right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | 11 | /** 12 | * @type of root: TreeNode 13 | * @type of req_sum: boolean 14 | * @return type: integer(1 if path sum exists else 0) 15 | */ 16 | class Solution { 17 | public: 18 | int pathSumExists(TreeNode* root, int req_sum) { 19 | // write your awesome code here 20 | if(!root) return req_sum == 0; 21 | req_sum -= root->val; 22 | if(pathSumExists(root->left, req_sum) || 23 | pathSumExists(root->right, req_sum)) 24 | return true; 25 | return false; 26 | } 27 | 28 | }; 29 | -------------------------------------------------------------------------------- /Interview Prep/Google/AfterAcademy/5. Greatest Common Divisor.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @type of num1: integer 3 | * @type of num2: integer 4 | * @return type: integer 5 | */ 6 | class Solution { 7 | public: 8 | int findGCD(int num1, int num2) { 9 | // write your awesome code here 10 | if(num1 < num2) swap(num1, num2); 11 | if(num2 == 0) return num1; 12 | return findGCD(num2, num1 % num2); 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Interview Prep/Google/AfterAcademy/9. Wave Array.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @type of arr: integer array 3 | * @return type: integer array 4 | */ 5 | class Solution { 6 | public: 7 | vector waveArray(vector& arr) { 8 | // write your awesome code here 9 | sort(arr.begin(),arr.end()); 10 | for(int i = 1; i < arr.size(); i+=2) swap(arr[i], arr[i-1]); 11 | return arr; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Interview Prep/Google/Validate Stack Sequences.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool validateStackSequences(vector& pushed, vector& popped) { 4 | stack s; 5 | int i = 0, j = 0 , n = pushed.size(); 6 | while(i < n && j < n) { 7 | if(!s.empty() && popped[j] == s.top()) { 8 | ++j; 9 | s.pop(); 10 | } else { 11 | s.push(pushed[i]); 12 | ++i; 13 | } 14 | } 15 | while(j < n) { 16 | if(s.top() != popped[j]) return false; 17 | s.pop(); ++j; 18 | } 19 | return true; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Leetcode DBMS/Consecutive Numbers.mysql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | # Using nested queries 3 | # select distinct num as ConsecutiveNums from Logs L1 4 | # where (id+2)<=(select MAX(id) from Logs) 5 | # AND 6 | # L1.num = (select num from Logs L2 where L1.id + 1 = L2.id ) 7 | # AND 8 | # L1.num = (select num from Logs L3 where L1.id + 2 = L3.id ) 9 | 10 | # Using Joins 11 | select distinct l1.num as ConsecutiveNums from Logs l1 12 | JOIN 13 | Logs l2 on l1.id+1 = l2.id 14 | JOIN 15 | Logs l3 on l1.id+2 = l3.id 16 | where 17 | l1.num = l2.num 18 | AND 19 | l2.num = l3.num; 20 | -------------------------------------------------------------------------------- /Leetcode DBMS/Delete Duplicate Emails.mysql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | delete p1 from Person p1 3 | INNER JOIN 4 | Person p2 5 | where p2.id < p1.id 6 | and 7 | p2.Email = p1.Email 8 | -------------------------------------------------------------------------------- /Leetcode DBMS/Department Highest Salary.mysql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select D1.Name as Department, E1.Name as Employee, E1.Salary as Salary from 3 | 4 | Employee E1 5 | JOIN 6 | Department D1 7 | ON 8 | E1.DepartmentId = D1.Id 9 | 10 | where E1.Salary = ( Select MAX(Salary) from Employee E2 Group by E2.DepartmentId having E2.DepartmentId=E1.DepartmentId); 11 | -------------------------------------------------------------------------------- /Leetcode DBMS/Department Top Three Salaries.mysql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | 3 | 4 | select D.Name as Department , E.Name as Employee, E.Salary as Salary 5 | from Employee E 6 | JOIN 7 | Department D 8 | ON 9 | E.DepartmentId = D.id 10 | where E.Salary IN 11 | ( 12 | select distinct Salary from Employee e1 13 | where 14 | e1.DepartmentId = D.Id 15 | AND 16 | 3 > 17 | ( 18 | select count(distinct Salary) from Employee e2 where e2.DepartmentId = e1.DepartmentId 19 | and e2.Salary > e1.Salary 20 | ) 21 | ) 22 | -------------------------------------------------------------------------------- /Leetcode DBMS/Duplicate Emails.mysql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | # Using nested query 3 | # select distinct p1.Email as Email from Person p1 4 | # where 1 < (select count(*) from Person p2 where p2.Email = p1.Email); 5 | 6 | # Using group by 7 | select Email from Person group by Email having Count(Email) > 1; 8 | -------------------------------------------------------------------------------- /Leetcode DBMS/Employees Earning More Than Their Managers.mysql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select Name as Employee from Employee e 3 | where e.ManagerId is not null 4 | AND 5 | e.Salary > ( Select Salary from Employee e2 where e2.id = e.ManagerId ) 6 | -------------------------------------------------------------------------------- /Leetcode DBMS/Nth Highest Salary.mysql: -------------------------------------------------------------------------------- 1 | CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT 2 | BEGIN 3 | RETURN ( 4 | # Write your MySQL query statement below. 5 | select distinct Salary from Employee E1 where N-1 = ( Select count(distinct Salary) from Employee E2 6 | where E1.salary< E2.salary) 7 | ); 8 | END 9 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/132 Pattern.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool find132pattern(vector& nums) { 4 | // 1 2 3 4 5 | stack< int > s; 6 | int second = INT_MIN; 7 | for(int i = nums.size()-1; i>=0; --i) { 8 | if(nums[i] < second) { 9 | return true; 10 | } 11 | while(!s.empty() && nums[i] > s.top() ) { 12 | second = s.top(); 13 | s.pop(); 14 | } 15 | s.push(nums[i]); 16 | } 17 | return false; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/3Sum With Multiplicity.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int threeSumMulti(vector& arr, int target) { 4 | int n = arr.size(), mxSum = 300; 5 | const int mod = 1e9 + 7; 6 | vector> twoSum(n, vector(mxSum+1, 0)); 7 | for(int i = 0; i < n; ++i) 8 | for(int j = 0; j < i; ++j) 9 | twoSum[i][arr[i] + arr[j]]++; 10 | 11 | for(int i = 1; i < n; ++i) 12 | for(int s = 0; s <= mxSum; ++s) 13 | twoSum[i][s] += twoSum[i-1][s]; 14 | 15 | long long int ans = 0; 16 | for(int i = 2; i < n; ++i) 17 | if(target >= arr[i]) 18 | ans = (ans + twoSum[i-1][target - arr[i]]) %mod; 19 | return ans % mod; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/4Sum II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int fourSumCount(vector& nums1, vector& nums2, vector& nums3, vector& nums4) { 4 | unordered_mapmp; 5 | int cnt =0; 6 | for(int i=0;i= 2; 11 | k++; 12 | } 13 | return (carry ? to_string(carry) : "") + res; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Add Digits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int addDigits(int num) { 4 | while(num > 9) { 5 | int sum = 0; 6 | while(num > 0) { 7 | sum += num%10; 8 | num/=10; 9 | } 10 | num = sum; 11 | } 12 | return num; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Add Strings.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string addStrings(string a, string b) { 4 | reverse(a.begin(), a.end()); 5 | reverse(b.begin(), b.end()); 6 | 7 | string res = ""; 8 | int n = a.length(), i = 0; 9 | int m = b.length(), j = 0; 10 | int carry = 0; 11 | while(!(i==n && j ==m && carry == 0)) { 12 | int d = carry; 13 | if(i < n) { 14 | d += a[i] - '0'; ++i; 15 | } 16 | if(j < m) { 17 | d += b[j] - '0'; ++j; 18 | } 19 | res += '0' + (d%10); 20 | carry = d/10; 21 | } 22 | 23 | reverse(res.begin(), res.end()); 24 | return res; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/All Paths From Source to Target.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> ans; 4 | void dfs(int u, vector &path, int dest, vector> &g) { 5 | path.push_back(u); 6 | if(u == dest) { 7 | ans.push_back(path); 8 | path.pop_back(); 9 | return; 10 | } 11 | for(int v : g[u]) 12 | dfs(v, path, dest, g); 13 | path.pop_back(); 14 | } 15 | vector> allPathsSourceTarget(vector>& graph) { 16 | vector path; 17 | dfs(0, path, graph.size()-1, graph); 18 | return ans; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Arithmetic Slices II - Subsequence.cpp: -------------------------------------------------------------------------------- 1 | using ll = long long; 2 | class Solution { 3 | public: 4 | int numberOfArithmeticSlices(vector& a) { 5 | int n = a.size(); 6 | int ans = 0; 7 | map< ll, int> dp[n]; 8 | // dp[i][ d ] = number of subseq ending at i, having difference d 9 | 10 | for(int i = 0; i < n; ++i) { 11 | for(int j = 0; j< i; ++j) { 12 | ll d = (ll)a[i] - (ll)a[j]; 13 | int cur = (dp[j].count(d) ? 1 + dp[j][d] : 1); 14 | dp[i][d] += cur; 15 | ans += cur; 16 | } 17 | } 18 | // subtract 2 length 19 | ans -= ((n-1)*(n))/2; 20 | return ans; 21 | 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Arithmetic Slices.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numberOfArithmeticSlices(vector& nums) { 4 | int n = nums.size(), i = 1; 5 | int ans = 0; 6 | 7 | while(i < n) { 8 | int j = i+1, d = nums[i] - nums[i-1]; 9 | while(j < n && d == nums[j]-nums[j-1]) ++j; 10 | // (j-i-1) + (j-i-2) + ... + 1 11 | ans += (j-i-1) * (j-i) / 2; 12 | i = j; 13 | } 14 | 15 | return ans; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Arranging Coins.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int arrangeCoins(long long n) { 4 | // (k*(k+1))/ 2 <= n 5 | // k*k + k <= 2*n 6 | long long k = sqrt(2ll*n); 7 | if(k*(k+1) <= 2ll*n) return k; 8 | return k-1; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Array Nesting.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int arrayNesting(vector& a) { 4 | int n = a.size(); 5 | vector vis(n , 0); 6 | int ans = 0; 7 | for(int i = 0; i < n; ++i) { 8 | if(!vis[i]) { 9 | int cur = i; 10 | int len = 0; 11 | while(!vis[cur]) { 12 | ++len; vis[cur] = 1; 13 | cur = a[cur]; 14 | } 15 | ans = max(ans, len); 16 | } 17 | } 18 | return ans; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Array of Doubled Pairs.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool solve(multiset &s) { 4 | while(s.size()!=0) { 5 | int u = *s.rbegin(); 6 | s.erase(s.find(u)); 7 | if(u&1) return false; 8 | int v = u/2; 9 | if(s.find(v) == s.end()) return false; 10 | s.erase(s.find(v)); 11 | } 12 | return true; 13 | } 14 | bool canReorderDoubled(vector& arr) { 15 | multiset pos, neg; 16 | for(auto &i : arr) if(i >= 0) pos.insert(i); else neg.insert(-i); 17 | return solve(pos) && solve(neg); 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Backspace String Compare.cpp: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Baseball Game.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int calPoints(vector& ops) { 4 | stack st; 5 | for(auto &s : ops) { 6 | if(s == "D") 7 | st.push(2*st.top()); 8 | else if(s == "+") { 9 | int x = st.top();st.pop(); 10 | int y = x + st.top(); 11 | st.push(x); 12 | st.push(y); 13 | } else if(s == "C") st.pop(); 14 | else st.push(stoi(s)); 15 | } 16 | int ans = 0; 17 | while(!st.empty()) { 18 | ans += st.top(); st.pop(); 19 | } 20 | return ans; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Best Time to Buy and Sell Stock II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector& prices) { 4 | int profit = 0; 5 | for(int i = 1; i < prices.size(); ++i) 6 | profit += max(0, prices[i]- prices[i-1]); 7 | return profit; 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Best Time to Buy and Sell Stock.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector& prices) { 4 | int mn = prices[0], maxProfit = 0; 5 | for(int p : prices) { 6 | mn = min(mn, p); 7 | maxProfit = max(maxProfit, p - mn); 8 | } 9 | return maxProfit; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Binary Search.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int search(vector& nums, int target) { 4 | int idx = lower_bound(nums.begin(), nums.end(), target) - nums.begin(); 5 | return idx == nums.size() || nums[idx] != target ? -1 : idx; 6 | } 7 | }; 8 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Binary Tree Pruning.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* pruneTree(TreeNode* root) { 15 | if(!root) 16 | return root; 17 | root->left = pruneTree(root->left); 18 | root->right = pruneTree(root->right); 19 | if(root->left || root->right) 20 | return root; 21 | if(root->val == 1) return root; 22 | return nullptr; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Binary Tree Tilt.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 dfs(TreeNode *root, int &ans) { 15 | if(!root) return 0; 16 | int L = dfs(root->left, ans), R = dfs(root->right, ans); 17 | ans += abs(L-R); 18 | return L+R+root->val; 19 | } 20 | int findTilt(TreeNode* root) { 21 | int ans = 0; 22 | dfs(root, ans); 23 | return ans; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Bitwise AND of Numbers Range.cpp: -------------------------------------------------------------------------------- 1 | using ll = long long; 2 | class Solution { 3 | public: 4 | int rangeBitwiseAnd(int left, int right) { 5 | int ans = 0; 6 | for(ll i=0;i<=30;i++){ 7 | ll a = (1LL<=l1 and right<=r1) 11 | ans+=a; 12 | } 13 | return (int)ans; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Boats to Save People.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numRescueBoats(vector& people, int limit) { 4 | multiset s(people.begin(), people.end()); 5 | int ans = 0; 6 | while(!s.empty()) { 7 | int a = *s.rbegin(); 8 | s.erase(s.find(a)); 9 | if(!s.empty() && *s.begin() <= limit - a) { 10 | int b = *prev(s.upper_bound(limit - a)); 11 | s.erase(s.find(b)); 12 | } 13 | ++ans; 14 | } 15 | return ans; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Break a Palindrome.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string breakPalindrome(string s) { 4 | int n = s.length(); 5 | if(n == 1) return ""; 6 | bool allA = true; 7 | for(int i = 0; i < n/2; ++i) { 8 | if(s[i] != 'a') { 9 | allA = false; 10 | s[i] = 'a'; 11 | break; 12 | } 13 | } 14 | if(allA) s[n-1] = 'b'; 15 | return s; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Broken Calculator.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int brokenCalc(int startValue, int target) { 4 | int ans = 0; 5 | while(target > startValue) { 6 | ++ans; 7 | (target&1) ? ++target : target/=2; 8 | } 9 | return ans + startValue - target; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Can Place Flowers.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canPlaceFlowers(vector& bed, int n) { 4 | for(int i = 0; i < bed.size(); ++i) { 5 | if(bed[i] == 0 && (i==0 || bed[i-1]==0) && (i==bed.size()-1 || bed[i+1] == 0)) { 6 | bed[i] = 1; --n; 7 | } 8 | // cout << bed[i] << " "; 9 | } 10 | return n <= 0; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Champagne Tower.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double champagneTower(int poured, int query_row, int query_glass) { 4 | if(query_row == 0) { 5 | return min(poured , 1); 6 | } 7 | vector< vector< double>> dp(105 , vector (105,0)); 8 | dp[0][0] = poured; 9 | for(int row = 1; row <= 100; ++row) { 10 | for(int i = 0 ; i < row; ++i) { 11 | if(dp[row-1][i] > 1 ) { 12 | dp[row][i] += (dp[row-1][i] - 1)/2.0; 13 | dp[row][i+1] += (dp[row-1][i] - 1)/2.0; 14 | } 15 | } 16 | } 17 | double &res = dp[query_row][query_glass]; 18 | if(res > 1 ) res = 1; 19 | return res; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Check If a String Contains All Binary Codes of Size K.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool hasAllCodes(string s, int k) { 4 | if(s.length() < k) return false; 5 | int cur = 0; 6 | for(int i = 0; i < k; ++i) 7 | cur = (cur<<1) + s[i]-'0'; 8 | vector present(1< dp(n + 1); 5 | dp[0] = dp[1] = 1; 6 | for(int i = 2; i <= n; ++i) dp[i] = dp[i-1] + dp[i-2]; 7 | return dp[n]; 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Clone Graph.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | map< Node* , Node*> vis; 4 | Node* cloneGraph(Node* node) { 5 | if(!node) 6 | return NULL; 7 | if(vis.find(node)!=vis.end()) 8 | return vis[node]; 9 | Node *copy = new Node(node->val); 10 | vis[node] = copy; 11 | copy->neighbors.resize(node->neighbors.size()); 12 | for(int i = 0; i < copy->neighbors.size(); ++i) { 13 | copy->neighbors[i] = cloneGraph(node->neighbors[i]); 14 | } 15 | return copy; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Coin Change.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int coinChange(vector& coins, int amount) { 4 | vector req(amount+1, amount+1); 5 | req[0] = 0; 6 | for(int a = 1; a <= amount; ++a) { 7 | for(int c : coins) 8 | if(c <= a) 9 | req[a] = min(req[a], 1 + req[a-c]); 10 | } 11 | return req[amount] <= amount ? req[amount] : -1; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Combination Sum III.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | vector> res; 3 | vector cur; 4 | public: 5 | void rec(int n, int k, int d) { 6 | if(d == 0) { 7 | if(k == 0 && n == 0) 8 | res.push_back(cur); 9 | return; 10 | } 11 | // dont take 12 | rec(n, k, d-1); 13 | // take 14 | cur.push_back(d); 15 | rec(n-d, k-1, d-1); 16 | cur.pop_back(); 17 | } 18 | vector> combinationSum3(int k, int n) { 19 | rec(n, k, 9); 20 | return res; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Compare Version Numbers.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int compareVersion(string a, string b) { 4 | int i = 0, j = 0, n = a.length(), m = b.length(); 5 | while(i < n || j < m) { 6 | int rev1 = 0, rev2 = 0; 7 | while(i < n && a[i] != '.') rev1 = rev1*10 + (a[i++]-'0'); 8 | while(j < m && b[j] != '.') rev2 = rev2*10 + (b[j++]-'0'); 9 | ++i, ++j; 10 | if(rev1 != rev2) 11 | return (rev1 - rev2) / abs(rev1 - rev2); 12 | } 13 | return 0; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Complement of Base 10 Integer.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int bitwiseComplement(int n) { 4 | return (n == 0 ? 1 : ((1<<(1+(int)log2(n)))-1)^n); 5 | } 6 | }; 7 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Consecutive Characters.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxPower(string s) { 4 | int ans = 1, cur = 1, p = '0'; 5 | for(char &c : s) { 6 | if(c == p) ++cur; 7 | else { 8 | ans = max(ans, cur); 9 | cur = 1; 10 | } 11 | p = c; 12 | } 13 | ans = max(ans, cur); 14 | return ans; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Contiguous Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMaxLength(vector& nums) { 4 | unordered_map idx; // idx[sum] = idx; 0:-1 5 | idx[0] = -1; 6 | int csum = 0, ans = 0; 7 | for(int i = 0; i < nums.size(); ++i) { 8 | csum += (nums[i] == 0 ? -1 : 1); 9 | if(idx.count(csum)) 10 | ans = max(ans, i - idx[csum]); 11 | else 12 | idx[csum] = i; 13 | } 14 | return ans; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Convert BST to Greater 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 dfs(TreeNode *root, int &sum) { 15 | if(!root) return; 16 | dfs(root->right, sum); 17 | sum += root->val; 18 | root->val = sum; 19 | dfs(root->left, sum); 20 | } 21 | TreeNode* convertBST(TreeNode* root) { 22 | int sum = 0; 23 | dfs(root, sum); 24 | return root; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Convert Binary Number in a Linked List to Integer.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 | int getDecimalValue(ListNode* head) { 14 | int ans = 0; 15 | while(head){ 16 | ans = (ans<<1) + head->val; 17 | head = head->next; 18 | } 19 | return ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Count All Valid Pickup and Delivery Options.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | const int MOD = 1e9 + 7; 5 | int sum(long long int n) { 6 | return ( ( (n+1) * n )/2) % MOD; 7 | } 8 | int countOrders(int n) { 9 | vector< long long int > dp(n + 1 , 0); 10 | dp[1] = 1; 11 | for(int i = 2; i <= n; ++i) { 12 | dp[i] = (dp[i-1] * sum(2 * i - 1) ) % MOD; 13 | } 14 | return (int)dp[n]; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Count Good Nodes in 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 good(TreeNode *root, int curmax) { 15 | if(!root) return 0; 16 | int ans = root->val >= curmax; 17 | curmax = max(curmax, root->val); 18 | return ans + good(root->left, curmax) + good(root->right, curmax); 19 | } 20 | int goodNodes(TreeNode* root) { 21 | return good(root, INT_MIN); 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Count Sorted Vowel Strings.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector< vector< int >> dp; 4 | int cnt(int n , int r) { 5 | 6 | 7 | int &ans = dp[n][r]; 8 | if(ans != -1) 9 | return ans; 10 | if(n == 0) 11 | return dp[n][r] = 1; 12 | ans = 0; 13 | for(int i = 1; i <= r; ++i) 14 | ans += cnt(n-1 , i); 15 | return ans; 16 | } 17 | int countVowelStrings(int n) { 18 | dp.assign(n+1, vector (6 , -1)); 19 | return cnt(n,5); 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Counting Bits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector countBits(int n) { 4 | vector ans(n+1); 5 | for(int i = 0; i <= n; ++i) 6 | ans[i] = __builtin_popcount(i); 7 | return ans; 8 | } 9 | };Counting Bits 10 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Custom Sort String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string customSortString(string order, string str) { 4 | map< char, int > m; 5 | for(auto &i : str) m[i]++; 6 | str = ""; 7 | for(auto &i : order) { 8 | str += string(m[i] , i); 9 | m.erase(i); 10 | } 11 | for(auto &i : m) str += string(i.second, i.first); 12 | cout << str; 13 | return str; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Daily Temperatures.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector dailyTemperatures(vector& t) { 4 | // rge 5 | int n = t.size(); 6 | vector rge(n, 0); 7 | stack s; 8 | for(int i = 0; i < n;) { 9 | if(s.empty() || t[i] <= t[s.top()]) { 10 | s.push(i++); 11 | } else { 12 | rge[s.top()] = i - s.top(); 13 | s.pop(); 14 | } 15 | } 16 | return rge; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Decode Ways.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numDecodings(string s) { 4 | int n = s.length(); 5 | int dp[n+1]; 6 | dp[0] = 1; 7 | for(int i = 1; i <= n; ++i) { 8 | dp[i] = 0; 9 | if(s[i-1] >= '1' && s[i-1] <= '9') 10 | dp[i] = dp[i-1]; // this digit as single 11 | if(i >= 2) { 12 | string pre = ""; pre+= s[i-2]; pre+= s[i-1]; 13 | if(stoi(pre) >= 1 && stoi(pre) <= 26 && s[i-2] > '0') 14 | dp[i] += dp[i-2]; 15 | } 16 | } 17 | return dp[n]; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Delete Operation for Two Strings.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | // L1 + L2 - 2 * LCS 4 | vector< vector> dp; 5 | int lcs(int i , int j , string &a, string &b) { 6 | if(i < 0 || j < 0) 7 | return 0; 8 | int &ret = dp[i][j]; 9 | if(ret != -1) 10 | return ret; 11 | 12 | if(a[i] == b[j]) return ret = 1 + lcs(i-1, j-1, a ,b); 13 | return ret = max(lcs(i-1, j , a , b), lcs(i, j-1, a, b)); 14 | } 15 | int minDistance(string a, string b) { 16 | int n = a.size(); 17 | int m = b.size(); 18 | dp.resize(n , vector (m, -1)); 19 | return m + n - 2 * lcs(n-1, m-1, a, b); 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Delete and Earn.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int deleteAndEarn(vector& nums) { 4 | map m; 5 | for(int i : nums) m[i]++; 6 | int dp0 = 0, dp1 = 0, prev = -1000; 7 | for(auto &i : m) { 8 | int newDp0 = max(dp0, dp1); 9 | int newDp1 = i.first * i.second + (prev == i.first-1 ? dp0 : newDp0); 10 | dp0 = newDp0; 11 | dp1 = newDp1; 12 | prev = i.first; 13 | } 14 | return max(dp0, dp1); 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Design HashMap.cpp: -------------------------------------------------------------------------------- 1 | class MyHashMap { 2 | public: 3 | vector hash; 4 | MyHashMap() { 5 | hash.assign(1e6+1, -1); 6 | } 7 | 8 | void put(int key, int value) { 9 | hash[key] = value; 10 | } 11 | 12 | int get(int key) { 13 | return hash[key]; 14 | } 15 | 16 | void remove(int key) { 17 | hash[key] = -1; 18 | } 19 | }; 20 | 21 | /** 22 | * Your MyHashMap object will be instantiated and called as such: 23 | * MyHashMap* obj = new MyHashMap(); 24 | * obj->put(key,value); 25 | * int param_2 = obj->get(key); 26 | * obj->remove(key); 27 | */ 28 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Design HashSet.cpp: -------------------------------------------------------------------------------- 1 | class MyHashSet { 2 | public: 3 | bool *hash; 4 | MyHashSet() { 5 | const int MX_KEY = 1e6; 6 | hash = new bool[MX_KEY + 1]; 7 | memset(hash, 0, sizeof(bool) * (MX_KEY + 1)); 8 | } 9 | 10 | void add(int key) { 11 | hash[key] = true; 12 | } 13 | 14 | void remove(int key) { 15 | hash[key] = false; 16 | } 17 | 18 | bool contains(int key) { 19 | return hash[key]; 20 | } 21 | }; 22 | 23 | /** 24 | * Your MyHashSet object will be instantiated and called as such: 25 | * MyHashSet* obj = new MyHashSet(); 26 | * obj->add(key); 27 | * obj->remove(key); 28 | * bool param_3 = obj->contains(key); 29 | */ 30 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Detect Capital.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | inline bool isCap(char c) { 4 | return c >= 'A' && c <= 'Z'; 5 | } 6 | bool detectCapitalUse(string word) { 7 | int cnt = 0; 8 | for(char c : word) 9 | cnt += isCap(c); 10 | return isCap(word[0]) ? (cnt == 1 || cnt == word.length()): cnt == 0; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Distinct Subsequences.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lcs(int i , int j , string &s , string &t , vector> &dp) { 4 | if(j==0) { 5 | return 1; 6 | } 7 | if(i==0) 8 | return 0; 9 | if(dp[i][j]!=-1) 10 | return dp[i][j]; 11 | int ans = 0; 12 | if(t[j-1] == s[i-1]) 13 | ans+= lcs(i-1 , j-1 , s , t , dp); 14 | ans+= lcs(i-1 , j , s, t , dp); 15 | dp[i][j] = ans; 16 | return ans; 17 | } 18 | int numDistinct(string s, string t) { 19 | vector> dp(s.length()+1 , vector (t.length()+1 , -1)); 20 | return lcs(s.length() , t.length() , s ,t , dp); 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Divide Two Integers.cpp: -------------------------------------------------------------------------------- 1 | using ll = long double; 2 | class Solution { 3 | public: 4 | int divide(int dividend, int divisor) { 5 | ll result=0; 6 | int sign = 1; 7 | if(dividend<0) sign *= -1; 8 | if(divisor<0) sign *= -1; 9 | if(divisor == 1 || dividend ==0) return dividend; 10 | 11 | ll a = dividend; 12 | ll b = divisor; 13 | 14 | if(a<0) a = abs(a); 15 | 16 | if(b<0) b = abs(b); 17 | 18 | if(a INT_MAX) return INT_MAX; 21 | return sign*result; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Domino and Tromino Tiling.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numTilings(int n) { 4 | /* 5 | __ || |- | 6 | __ | |_ 7 | 8 | 0 = flat 9 | 1 = r 10 | 2 = L 11 | */ 12 | const int MOD = 1e9+7; 13 | array pre1 = {1,0,0}, pre2 = {0,0,0}, cur; 14 | 15 | for(int i = 1; i <= n; ++i) { 16 | // flat 17 | cur[0] = (pre1[0] + pre2[0] + pre1[1] + pre1[2]) % MOD; 18 | // r 19 | cur[1] = (pre1[2] + pre2[0]) % MOD; 20 | // L 21 | cur[2] = (pre1[1] + pre2[0]) % MOD; 22 | 23 | swap(pre2, pre1); 24 | swap(cur, pre1); 25 | } 26 | return pre1[0]; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Encode and Decode TinyURL.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | unordered_map hash; 4 | int cnt = 0; 5 | // Encodes a URL to a shortened URL. 6 | string encode(string longUrl) { 7 | hash[cnt] = longUrl; 8 | string ret = to_string(cnt++); 9 | return ret; 10 | } 11 | 12 | // Decodes a shortened URL to its original URL. 13 | string decode(string shortUrl) { 14 | return hash[stoi(shortUrl)]; 15 | } 16 | }; 17 | 18 | // Your Solution object will be instantiated and called as such: 19 | // Solution solution; 20 | // solution.decode(solution.encode(url)); 21 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Excel Sheet Column Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int titleToNumber(string columnTitle) { 4 | int ans = 0; 5 | for(char c : columnTitle) { 6 | ans = ans * 26 + (c - 'A' + 1); 7 | } 8 | return ans; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Find All Anagrams in a String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findAnagrams(string s, string p) { 4 | vector fp(26,0); 5 | for(char c : p) 6 | fp[c-'a']++; 7 | int np = p.length(), ns = s.length(); 8 | vector fs(26,0); 9 | vector res; 10 | if(ns < np) return res; 11 | for(int i = 0; i < np-1; ++i) 12 | fs[s[i]-'a']++; 13 | for(int i = np-1; i < ns; ++i) { 14 | fs[s[i]-'a']++; 15 | if(fp == fs) res.push_back(i+1 - np); 16 | fs[s[i+1-np]-'a']--; 17 | } 18 | return res; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Find All Duplicates in an Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findDuplicates(vector& nums) { 4 | vector r; 5 | int n = nums.size(); 6 | for(int i = 0; i < n; ++i) { 7 | int v = abs(nums[i]); 8 | if(nums[v-1] < 0) r.push_back(v); 9 | else nums[v-1] = -nums[v-1]; 10 | } 11 | return r; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Find All Numbers Disappeared in an Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findDisappearedNumbers(vector& nums) { 4 | int n = nums.size(); 5 | for(int i = 0; i < n; ++i) { 6 | nums[abs(nums[i])-1] = - abs(nums[abs(nums[i])-1]); 7 | } 8 | vector res; 9 | for(int i = 0; i < n; ++i) 10 | if(nums[i] > 0) res.push_back(i+1); 11 | return res; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Find Minimum in Rotated Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMin(vector& a) { 4 | int n = a.size(); 5 | // chk if already sorted 6 | if(a[0] < a[n-1]) return a[0]; 7 | //find the rotating point 8 | int lo = 0 , hi = n-1; 9 | int idx = -1; 10 | while( lo <= hi ) { 11 | int mid = (lo+hi)/2; 12 | if(a[mid] > a[(mid+1)%n]) { 13 | idx = mid; break; 14 | } else if(a[mid] >= a[0]) { 15 | lo = mid + 1; // we are in left of rotation point 16 | } else { 17 | hi = mid - 1; // we are in right of rotation point 18 | } 19 | } 20 | return a[(idx + 1)%n]; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Find Peak Element.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findPeakElement(vector& a) { 4 | int n = a.size(); 5 | if(n == 1) return 0; 6 | int lo = 0, hi = n-1; 7 | while( lo <= hi ){ 8 | int mid = lo + (hi-lo)/2; 9 | bool peak = (mid == 0 ? 1: a[mid] > a[mid-1]) && (mid==n-1 ? 1 : a[mid]>a[mid+1]); 10 | if( peak ) 11 | return mid; 12 | else if( mid==0 || a[mid+1] > a[mid-1] ) lo = mid+1; 13 | else hi = mid-1; 14 | } 15 | return -1; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Find a Corresponding Node of a Binary Tree in a Clone of That Tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | 11 | class Solution { 12 | public: 13 | TreeNode *dfs(TreeNode *u, TreeNode *v, TreeNode *k) { 14 | if(!u) return nullptr; 15 | if(u->val == k->val) 16 | return v; 17 | TreeNode *L = dfs(u->left, v->left, k); 18 | if(L) return L; 19 | return dfs(u->right, v->right, k); 20 | } 21 | TreeNode* getTargetCopy(TreeNode* original, TreeNode* cloned, TreeNode* target) { 22 | return dfs(original, cloned, target); 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Find the Difference.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | char findTheDifference(string s, string t) { 4 | char ans = 0; 5 | for(char c : s) ans ^= c; 6 | for(char c : t) ans ^= c; 7 | return ans; 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Find the Duplicate Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findDuplicate(vector& nums) { 4 | int low = 1, high = nums.size() - 1, cnt; 5 | 6 | while(low <= high) 7 | { 8 | int mid = low + (high - low) / 2; 9 | cnt = 0; 10 | for(int n : nums) 11 | if(n <= mid) 12 | ++cnt; 13 | if(cnt <= mid) 14 | low = mid + 1; 15 | else 16 | high = mid - 1; 17 | } 18 | return low; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Find the Town Judge.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findJudge(int n, vector>& trust) { 4 | vector in(n+1, 0); 5 | unordered_map m; 6 | for(auto p : trust) { 7 | in[p[1]]++; 8 | m[p[0]] = p[1]; 9 | } 10 | int ans = -1; 11 | for(int i = 1; i <= n; ++i) { 12 | if(in[i] == n-1) { 13 | if(ans == -1 && m.count(i) == 0) { 14 | ans = i; 15 | } else return -1; 16 | } 17 | } 18 | return ans; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Flip String to Monotone Increasing.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minFlipsMonoIncr(string s) { 4 | int lz = 0, lo = 0, rz = count(s.begin(), s.end(), '0'), ro = count(s.begin(), s.end(), '1'); 5 | int ans = s.length(); 6 | for(int i = 0; i < s.length(); ++i) { 7 | ans = min(ans, lo + rz); 8 | if(s[i] == '0') {++lz; --rz;} 9 | else if(s[i]=='1') {++lo; --ro;}; 10 | } 11 | ans = min(ans, lo + rz); 12 | return ans; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Gas Station.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int canCompleteCircuit(vector& gas, vector& cost) { 4 | int totalGas=0, currGas=0, ans=0; 5 | for(int i=0; i> groupAnagrams(vector& strs) { 4 | vector> g; 5 | map, vector> m; 6 | for(auto &i : strs) { 7 | vector f(26, 0); 8 | for(auto &j : i) f[j-'a']++; 9 | m[f].push_back(i); 10 | } 11 | vector> res; 12 | for(auto &i : m) res.push_back(i.second); 13 | return res; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Guess Number Higher or Lower.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Forward declaration of guess API. 3 | * @param num your guess 4 | * @return -1 if num is lower than the guess number 5 | * 1 if num is higher than the guess number 6 | * otherwise return 0 7 | * int guess(int num); 8 | */ 9 | 10 | class Solution { 11 | public: 12 | int guessNumber(int n) { 13 | int lo = 1, hi = n; 14 | while(lo <= hi) { 15 | int mid = lo + (hi-lo)/2; 16 | int g = guess(mid); 17 | if(g == 0) return mid; 18 | if(g < 0) hi = mid-1; 19 | else lo = mid + 1; 20 | } 21 | return 0; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Hamming Distance.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int hammingDistance(int x, int y) { 4 | return __builtin_popcount(x^y); 5 | } 6 | }; 7 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/House Robber.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int rob(vector& nums) { 4 | int rob0 = 0, rob1 = 0; 5 | for(int i : nums) { 6 | int rob2 = max(rob0 + i, rob1); 7 | rob0 = rob1; 8 | rob1 = rob2; 9 | } 10 | return rob1; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Implement Stack using Queues.cpp: -------------------------------------------------------------------------------- 1 | class MyStack { 2 | public: 3 | vector s; 4 | MyStack() { 5 | 6 | } 7 | 8 | void push(int x) { 9 | s.push_back(x); 10 | } 11 | 12 | int pop() { 13 | int v = s.back(); 14 | s.pop_back(); 15 | return v; 16 | } 17 | 18 | int top() { 19 | return s.back(); 20 | } 21 | 22 | bool empty() { 23 | return s.size() == 0; 24 | } 25 | }; 26 | 27 | /** 28 | * Your MyStack object will be instantiated and called as such: 29 | * MyStack* obj = new MyStack(); 30 | * obj->push(x); 31 | * int param_2 = obj->pop(); 32 | * int param_3 = obj->top(); 33 | * bool param_4 = obj->empty(); 34 | */ 35 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Insert into 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* insertIntoBST(TreeNode* root, int val) { 15 | if(!root) { 16 | return new TreeNode(val); 17 | } 18 | if(root->val > val) root->left = insertIntoBST(root->left, val); 19 | if(root->val < val) root->right = insertIntoBST(root->right, val); 20 | return root; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Intersection of Two Arrays II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector intersect(vector& a, vector& b) { 4 | sort(a.begin(), a.end()); 5 | sort(b.begin(), b.end()); 6 | vector c; 7 | int i = 0, j = 0; 8 | while(i < a.size() && j < b.size()) { 9 | if(a[i] == b[j]) { 10 | c.push_back(a[i]); ++i; ++j; 11 | } else if(a[i] < b[j]) ++i; 12 | else ++j; 13 | } 14 | return c; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Interval List Intersections.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> intervalIntersection(vector>& firstList, vector>& secondList) { 4 | vector> res; 5 | int n = firstList.size(); 6 | int m = secondList.size(); 7 | if(n == 0 || m == 0) return res; 8 | int i = 0, j = 0; 9 | while(i < n && j < m) { 10 | /* 11 | l1 r1 l2 r2 12 | */ 13 | int L = max(firstList[i][0], secondList[j][0]); 14 | int R = min(firstList[i][1], secondList[j][1]); 15 | if(L<=R) res.push_back({L,R}); 16 | if(firstList[i][1] < secondList[j][1]) ++i; 17 | else ++j; 18 | } 19 | return res; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/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 | TreeNode* invertTree(TreeNode* root) { 15 | if(!root) return root; 16 | TreeNode *L = invertTree(root->left); 17 | root->left = invertTree(root->right); 18 | root->right = L; 19 | return root; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Is Graph Bipartite?.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool bipartite(int u, vector &col, vector> &g) { 4 | for(int v : g[u]) { 5 | if(col[v] == -1) { 6 | col[v] = 1 - col[u]; 7 | if(!bipartite(v, col, g)) 8 | return false; 9 | } else if(col[u] == col[v]) 10 | return false; 11 | } 12 | return true; 13 | } 14 | bool isBipartite(vector>& graph) { 15 | int n = graph.size(); 16 | vector col(n, -1); 17 | for(int i = 0; i < n; ++i) 18 | if(col[i] == -1) { 19 | col[i] = 0; 20 | if(!bipartite(i, col, graph)) 21 | return false; 22 | } 23 | return true; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Is Subsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isSubsequence(string s, string t) { 4 | int i = 0, j = 0, n = s.length(), m = t.length(); 5 | while(i < n && j < m) { 6 | if(s[i] == t[j]) ++i, ++j; 7 | else ++j; 8 | } 9 | return i == n; 10 | } 11 | };Is Subsequence 12 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Isomorphic Strings.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isIsomorphic(string s, string t) { 4 | if(s.length() != t.length()) 5 | return false; 6 | map< char , char> m , rm; 7 | for(int i = 0; i < s.length(); ++i) { 8 | if(m.count(s[i])) { 9 | if(m[s[i]] != t[i]) 10 | return false; 11 | } else { 12 | if(rm.count(t[i])) return false; 13 | rm[t[i]] = s[i]; 14 | m[s[i]] = t[i]; 15 | } 16 | } 17 | return true; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Jump Game III.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canReach(vector& arr, int start) { 4 | int n = arr.size(); 5 | vector vis(n, false); 6 | queue q; 7 | q.push(start); 8 | vis[start] = 1; 9 | while(!q.empty()) { 10 | int u = q.front(); q.pop(); 11 | if(arr[u] == 0) return true; 12 | if(u>=arr[u] && !vis[u-arr[u]]) { 13 | q.push(u-arr[u]); 14 | vis[u-arr[u]] = 1; 15 | } 16 | if(u+arr[u]& nums) { 4 | int canGo = 0; 5 | for(int i = 0; i < nums.size(); ++i) { 6 | if(i > canGo) return false; 7 | canGo = max(canGo, i + nums[i]); 8 | } 9 | return true; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/K Closest Points to Origin.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> kClosest(vector>& points, int k) { 4 | priority_queue> pq; 5 | int d; 6 | for(auto &p : points) { 7 | d = p[0]*p[0] + p[1]*p[1]; 8 | if(pq.size() < k) { 9 | pq.push({d, p[0], p[1]}); 10 | } else if(pq.top()[0] > d) { 11 | pq.pop(); 12 | pq.push({d, p[0], p[1]}); 13 | } 14 | } 15 | vector> res; 16 | while(!pq.empty()) { 17 | res.push_back({pq.top()[1], pq.top()[2]}); 18 | pq.pop(); 19 | } 20 | return res; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/K-diff Pairs in an Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findPairs(vector& nums, int k) { 4 | unordered_set s; 5 | set> res; 6 | int ans = 0; 7 | for(int i : nums) { 8 | if(s.count(i-k)) 9 | res.insert({i-k, i}); 10 | if(s.count(i+k)) 11 | res.insert({i, i+k}); 12 | s.insert(i); 13 | } 14 | // for(auto p : res) cout << p.first << " " << p.second << endl; 15 | return res.size(); 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Koko Eating Bananas.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minEatingSpeed(vector& piles, int h) { 4 | int n = piles.size(); 5 | int lo = 1, hi = 1e9 + 10; 6 | while( lo <= hi ) { 7 | int mid = (lo + hi)/2; 8 | int time = 0; 9 | for(int p : piles) 10 | time += (p + mid-1)/mid; 11 | if(time > h) { 12 | lo = mid + 1; 13 | } else { 14 | hi = mid - 1; 15 | } 16 | } 17 | return hi + 1; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Kth Largest Element in a Stream.cpp: -------------------------------------------------------------------------------- 1 | class KthLargest { 2 | public: 3 | int k; 4 | priority_queue, greater> pq; 5 | KthLargest(int k, vector& nums) { 6 | this->k = k; 7 | for(int i : nums) add(i); 8 | } 9 | 10 | int add(int val) { 11 | if(pq.size() < k) pq.push(val); 12 | else if(pq.top() < val) { 13 | pq.pop(); pq.push(val); 14 | } 15 | return pq.top(); 16 | } 17 | }; 18 | 19 | /** 20 | * Your KthLargest object will be instantiated and called as such: 21 | * KthLargest* obj = new KthLargest(k, nums); 22 | * int param_1 = obj->add(val); 23 | */ 24 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Kth Largest Element in an Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findKthLargest(vector& nums, int k) { 4 | priority_queue, greater> pq; 5 | for(int i : nums) { 6 | if(pq.size() == k && pq.top() < i) pq.pop(); 7 | if(pq.size() < k) pq.push(i); 8 | } 9 | return pq.top(); 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Kth Smallest Number in Multiplication Table.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findKthNumber(int m, int n, int k) { 4 | int lo = 1, hi = m * n; 5 | while(lo <= hi) { 6 | int mid = (lo + hi)/2; 7 | int cnt = 0; 8 | for(int i = 1; i <= m; ++i) 9 | cnt += min(mid/i, n); 10 | if(cnt < k) lo = mid + 1; 11 | else hi = mid - 1; 12 | } 13 | return hi + 1; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Last Stone Weight.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lastStoneWeight(vector& stones) { 4 | priority_queue pq(stones.begin(), stones.end()); 5 | while(pq.size() > 1) { 6 | int u = pq.top(); pq.pop(); 7 | int v = pq.top(); pq.pop(); 8 | if(u==v) continue; 9 | pq.push(u-v); 10 | } 11 | return pq.empty() ? 0 : pq.top(); 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Letter Combinations of a Phone Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | vector l{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; 3 | vector res; 4 | public: 5 | void rec(int i, string &d, string &cur) { 6 | if(i == d.length()) { 7 | res.push_back(cur); 8 | return; 9 | } 10 | for(char c : l[d[i]-'0']) { 11 | cur += c; 12 | rec(i+1, d, cur); 13 | cur.pop_back(); 14 | } 15 | } 16 | vector letterCombinations(string digits) { 17 | if(digits == "") 18 | return res; 19 | res.clear(); 20 | string cur = ""; 21 | rec(0, digits, cur); 22 | return res; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/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 | ListNode *slow = head, *fast = head; 13 | while(fast && fast->next) { 14 | slow = slow->next; 15 | fast = fast->next->next; 16 | if(slow == fast) 17 | return true; 18 | } 19 | return false; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Longest Common Subsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> dp; 4 | int lcs(int i, int j, string &a, string &b) { 5 | if(i < 0 || j < 0) return 0; 6 | if(dp[i][j] != -1) return dp[i][j]; 7 | if(a[i] == b[j]) return dp[i][j] = 1 + lcs(i-1,j-1,a,b); 8 | return dp[i][j] = max(lcs(i-1,j,a,b), lcs(i,j-1,a,b)); 9 | } 10 | int longestCommonSubsequence(string text1, string text2) { 11 | dp.resize(text1.size(), vector(text2.size(),-1)); 12 | return lcs(text1.size()-1, text2.size()-1, text1, text2); 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Longest Substring Without Repeating Characters.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lengthOfLongestSubstring(string s) { 4 | int i = 0, j = 0, n = s.length(), ans = 0; 5 | bitset<256> seen(0); 6 | while(j < n) { 7 | if(seen[s[j]]) { 8 | ans = max(ans, j-i); 9 | while(seen[s[j]]) 10 | seen[s[i++]] = 0; 11 | j = max(j, i); 12 | } 13 | else 14 | seen[s[j++]] = 1; 15 | } 16 | ans = max(ans, j-i); 17 | return ans; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Longest Turbulent Subarray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxTurbulenceSize(vector& a) { 4 | int n = a.size(); 5 | vector< int > dp[2]; // dp[0][i] // prev element was smaller , dp[0][1] => prev element was larger 6 | 7 | dp[0].resize(n , 1); 8 | dp[1] = dp[0]; 9 | int ans = 1; 10 | for(int i = 1; i < n; ++i) { 11 | if(a[i] > a[i-1]) 12 | dp[0][i] = 1 + dp[1][i-1]; 13 | if(a[i] < a[i-1]) 14 | dp[1][i] = 1 + dp[0][i-1]; 15 | ans = max(ans, max(dp[0][i] , dp[1][i])); 16 | } 17 | return ans; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Lowest Common Ancestor of 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(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | 11 | class Solution { 12 | public: 13 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 14 | if(p->val > q->val) swap(p , q); 15 | if(root->val < p->val) 16 | return lowestCommonAncestor(root->right, p , q); 17 | if(root->val > q->val) 18 | return lowestCommonAncestor(root->left, p , q); 19 | return root; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Majority Element.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int majorityElement(vector& nums) { 4 | int e = -1, v = 1; 5 | for(int i : nums) { 6 | if(e != i) v--; 7 | else ++v; 8 | if(v == 0) { 9 | e = i; 10 | v = 1; 11 | } 12 | } 13 | return e; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Max Consecutive Ones.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMaxConsecutiveOnes(vector& nums) { 4 | int ans=0; 5 | int cur = 0; 6 | for(auto &i : nums) { 7 | if(i == 0) cur = 0; 8 | else ans = max(ans, ++cur); 9 | } 10 | return ans; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Max Number of K-Sum Pairs.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxOperations(vector& nums, int k) { 4 | unordered_map m; 5 | int ans = 0; 6 | for(int i : nums) { 7 | if(m.count(i)) { 8 | if(m[i] == 1) 9 | m.erase(i); 10 | else 11 | m[i]--; 12 | ++ans; 13 | } else 14 | m[k-i]++; 15 | } 16 | return ans; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Maximize Distance to Closest Person.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxDistToClosest(vector& seats) { 4 | int prev = -1, ans = 0; 5 | for(int i = 0; i < seats.size(); ++i) { 6 | if(seats[i] == 1) { 7 | if(prev == -1) ans = max(ans, i); 8 | else ans = max(ans, (i-prev)/2); 9 | prev = i; 10 | } 11 | } 12 | ans = max(ans, (int)seats.size()-1-prev); 13 | return ans; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/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) return 0; 16 | return 1 + max(maxDepth(root->left), maxDepth(root->right)); 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Maximum Erasure Value.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maximumUniqueSubarray(vector& nums) { 4 | int sum = 0, ans = 0, i = 0, j = 0, n = nums.size(); 5 | unordered_set seen; 6 | while(j < n) { 7 | if(seen.count(nums[j])) { 8 | ans = max(ans, sum); 9 | sum -= nums[i]; 10 | j = max(j, i); 11 | seen.erase(nums[i++]); 12 | } else { 13 | sum += nums[j]; 14 | seen.insert(nums[j++]); 15 | } 16 | } 17 | ans = max(ans, sum); 18 | return ans; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Maximum Number of Balloons.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxNumberOfBalloons(string text) { 4 | vector f1(26,0), f2(26, 0); 5 | const string pat = "balloon"; 6 | for(char i : pat) f1[i-'a']++; 7 | for(char i : text) f2[i-'a']++; 8 | int ans = INT_MAX; 9 | for(int i = 0; i < 26; ++i) { 10 | if(f1[i]) ans = min(ans, f2[i]/f1[i]); 11 | } 12 | return ans; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Maximum Product Subarray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProduct(vector& nums) { 4 | int mxNeg = INT_MIN; 5 | int pref = 1, ans = INT_MIN; 6 | for(int i : nums) { 7 | pref *= i; 8 | if(mxNeg != INT_MIN) 9 | ans = max(ans, pref / mxNeg); 10 | ans = max(ans, pref); 11 | if(pref == 0) { 12 | mxNeg = INT_MIN; 13 | pref = 1; 14 | } else 15 | mxNeg = (pref < 0 && pref > mxNeg ? pref : mxNeg); 16 | } 17 | return ans; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Maximum Product of Word Lengths.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProduct(vector& w) { 4 | int n = w.size(); 5 | int mask[n]; 6 | for(int i = 0; i < n; ++i) { 7 | mask[i] = 0; 8 | for(char c : w[i]) { 9 | mask[i] |= 1 << (c - 'a'); 10 | } 11 | } 12 | int ans = 0; 13 | for(int i = 0; i < n; ++i) { 14 | for(int j = i+1; j < n; ++j) { 15 | if((mask[i] & mask[j]) == 0) 16 | ans = max(ans, (int)(w[i].length() * w[j].length())); 17 | } 18 | } 19 | return ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Maximum Subarray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxSubArray(vector& nums) { 4 | int ans = nums[0]; 5 | int csum = 0; 6 | for(int i : nums) { 7 | csum += i; 8 | ans = max(ans, csum); 9 | csum = max(csum, 0); 10 | } 11 | return ans; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Maximum Width of Binary Tree.CPP: -------------------------------------------------------------------------------- 1 | using ull = unsigned long long; 2 | class Solution { 3 | public: 4 | int widthOfBinaryTree(TreeNode* root) { 5 | unordered_map firstIndex; 6 | return dfs(root, 0, 0, firstIndex); 7 | } 8 | ull dfs(TreeNode* root, int level, ull index, unordered_map& firstIndex) { 9 | if(!root) return 0; 10 | if(firstIndex.find(level) == firstIndex.end()) { 11 | firstIndex[level] = index; 12 | } 13 | ull left = dfs(root->left, level + 1, 2 * index, firstIndex); 14 | ull right = dfs(root->right, level + 1, 2 * index + 1, firstIndex); 15 | return max(index - firstIndex[level] + 1, max(left, right)); 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Merge Intervals.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> merge(vector>& a) { 4 | sort(a.begin(), a.end()); 5 | int st = a[0][0], en = a[0][1]; 6 | vector> res; 7 | for(int i = 1; i < a.size(); ++i) { 8 | if(en < a[i][0]) { 9 | res.push_back({st, en}); 10 | st = a[i][0]; 11 | en = a[i][1]; 12 | } else en = max(en, a[i][1]); 13 | } 14 | res.push_back({st, en}); 15 | return res; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Merge Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void merge(vector& nums1, int m, vector& nums2, int n) { 4 | int mergedIndex { m + n - 1}; 5 | int larger; 6 | 7 | while(m && n) { 8 | if( nums2[n - 1] > nums1[m - 1] ) larger = nums2[--n]; 9 | else larger = nums1[--m]; 10 | nums1[mergedIndex--] = larger; 11 | } 12 | while(m) nums1[mergedIndex--] = nums1[--m]; 13 | while(n) nums1[mergedIndex--] = nums2[--n]; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Merge k Sorted Lists.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* merge2Lists(ListNode* A , ListNode* B) { 4 | if(!A && !B) 5 | return nullptr; 6 | if(!A) 7 | return B; 8 | if(!B) 9 | return A; 10 | if(A->val > B->val) { 11 | B->next = merge2Lists(A , B->next); 12 | return B; 13 | } 14 | else { 15 | A->next = merge2Lists(A->next , B); 16 | return A; 17 | } 18 | } 19 | ListNode* mergeKLists(vector& lists) { 20 | if(lists.size() == 0) 21 | return nullptr; 22 | ListNode *R = lists[0]; 23 | for(int i = 1; i < lists.size(); ++i) { 24 | R = merge2Lists(R , lists[i]); 25 | } 26 | return R; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/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 | ListNode *slow = head, *fast = head; 15 | while(fast && fast->next) { 16 | slow = slow->next; 17 | fast = fast->next->next; 18 | } 19 | return slow; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Minimize Deviation in Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minimumDeviation(vector& nums) { 4 | set s; 5 | for(int i : nums) 6 | if(i&1) s.insert(2*i); 7 | else s.insert(i); 8 | int ans = INT_MAX; 9 | while(true) { 10 | int mx = *s.rbegin(), mn = *s.begin(); 11 | ans = min(ans, mx - mn); 12 | if(mx%2 == 0) { 13 | s.erase(mx); 14 | mx/=2; 15 | s.insert(mx); 16 | } else 17 | break; 18 | } 19 | return ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Minimum Absolute Difference.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> minimumAbsDifference(vector& arr) { 4 | 5 | vector> ans; 6 | sort(arr.begin(), arr.end()); 7 | int minDif = INT_MAX; 8 | for(int i = 1; i < arr.size(); i++) { 9 | int d = arr[i] - arr[i - 1]; 10 | if(d < minDif) { 11 | ans.clear(); 12 | minDif = d; 13 | ans.push_back({arr[i - 1], arr[i]}); 14 | } 15 | else if(d == minDif) { 16 | ans.push_back({arr[i - 1], arr[i]}); 17 | } 18 | } 19 | return ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Minimum Cost to Move Chips to The Same Position.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minCostToMoveChips(vector& position) { 4 | int c[2] = {0}; 5 | for(int i : position) 6 | c[i&1] ++; 7 | return min(c[0], c[1]); 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Minimum Domino Rotations For Equal Row.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minDominoRotations(vector& tops, vector& bottoms) { 4 | int ans = tops.size(); 5 | for(int v = 1; v <= 6; ++v) { 6 | int up = 0, bot = 0; 7 | for(int i = 0; i < tops.size(); ++i) { 8 | if(tops[i] != v && bottoms[i]!= v) { 9 | up = bot = tops.size(); 10 | break; 11 | } 12 | up += tops[i] != v; 13 | bot += bottoms[i] != v; 14 | } 15 | ans = min(ans, up); 16 | ans = min(ans, bot); 17 | } 18 | 19 | if(ans == tops.size()) 20 | return -1; 21 | return ans; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Minimum Number of Arrows to Burst Balloons.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMinArrowShots(vector>& points) { 4 | sort(points.begin(), points.end()); 5 | int ans = 0, i = 0, n = points.size(), shoot; 6 | int minEnding[n]; 7 | minEnding[n-1] = points[n-1][1]; 8 | for(int i = n-2; i >= 0; --i) 9 | minEnding[i] = min(minEnding[i+1], points[i][1]); 10 | 11 | while(i& nums) { 4 | int mn = 0, sum = 0; 5 | for(int i : nums) { 6 | sum += i; 7 | mn = min(mn, sum); 8 | } 9 | return -mn + 1; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Missing Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int missingNumber(vector& nums) { 4 | int ans = nums.size(); 5 | for(int i = nums.size()-1; i >= 0; --i) 6 | ans ^= i ^ nums[i]; 7 | return ans; 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/N-th Tribonacci Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int tribonacci(int n) { 4 | vector dp(n+3); 5 | dp[0] = 0; 6 | dp[1] = dp[2] = 1; 7 | for(int i = 3; i <= n; ++i) dp[i] = dp[i-1] + dp[i-2] + dp[i-3]; 8 | return dp[n]; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Nth Magical Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int nthMagicalNumber(int n, int a, int b) { 4 | long long lo = 1, hi = 4e13 + 10, mid, cnt; 5 | const int MOD = 1e9 + 7; 6 | int lcm = a*b/__gcd(a,b); 7 | while(lo <= hi) { 8 | mid = lo + (hi-lo)/2; 9 | cnt = (mid/a) + (mid/b) - (mid/lcm); 10 | if(cnt < n) 11 | lo = mid+1; 12 | else 13 | hi = mid-1; 14 | } 15 | return (hi+1)%MOD; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Number Complement.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findComplement(int num) { 4 | return (1ll<<(1+(int)log2(num))) - num-1; 5 | } 6 | }; 7 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Number of 1 Bits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int hammingWeight(uint32_t n) { 4 | int ans = 0; 5 | while(n != 0) { 6 | ++ans; 7 | n &= n-1; 8 | } 9 | return ans; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Number of Steps to Reduce a Number to Zero.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numberOfSteps(int num) { 4 | int ans = 0; 5 | while(num != 0) { 6 | if(num&1) num^=1; 7 | else num>>=1; 8 | ++ans; 9 | } 10 | return ans; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Orderly Queue.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string orderlyQueue(string s, int k) { 4 | if(k == 1) { 5 | // only rotations are possible 6 | string res = s; 7 | for(int i = 1; i < s.length(); ++i) { 8 | s = s.substr(1) + s[0]; 9 | res = min(res, s); 10 | } 11 | return res; 12 | } else { 13 | // all possible arrangements of string are possible 14 | sort(s.begin(), s.end()); 15 | return s; 16 | } 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Pairs of Songs With Total Durations Divisible by 60.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numPairsDivisibleBy60(vector& time) { 4 | vector f(60, 0); 5 | int ans = 0; 6 | for(int t : time) { 7 | t%=60; 8 | ans += f[(60-t)%60]; 9 | f[t]++; 10 | } 11 | return ans; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Palindromic Substrings.cpp: -------------------------------------------------------------------------------- 1 | const int NAX = 1e3 + 5; 2 | class Solution { 3 | public: 4 | int P[NAX][NAX]; 5 | bool pal(int i , int j , string &s) { 6 | int &ret = P[i][j]; 7 | if(ret != -1) 8 | return ret; 9 | if(j-i == 1) { 10 | return ret = (s[i] == s[j]); 11 | } 12 | return ret = (s[i]==s[j] && pal(i + 1 , j-1 , s)); 13 | } 14 | int countSubstrings(string s) { 15 | memset(P , -1 , sizeof P); 16 | for(int i = 0 ; i < s.length(); ++i) 17 | P[i][i] = 1; 18 | int ans = 0; 19 | for(int i = 0 ; i < s.length(); ++i) { 20 | for(int j = i; j < s.length(); ++j) { 21 | if(pal(i, j , s)) 22 | ++ans; 23 | } 24 | } 25 | return ans; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Partition Array into Disjoint Intervals.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int partitionDisjoint(vector& a) { 4 | multiset R; 5 | for(auto &i : a) R.insert(i); 6 | int ans = a.size()-1; 7 | multiset L; 8 | for(int i = 0; i & a) { 4 | int sum = accumulate(a.begin(), a.end(), 0); 5 | if( sum & 1 ) 6 | return false; 7 | // using bitsets 8 | bitset< 200*100 + 1 > b; 9 | b[0] = 1; 10 | for(auto &i : a) 11 | b |= b << i; 12 | return b[sum/2]; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Partition Labels.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector partitionLabels(string s) { 4 | vector rpos(26, 0); 5 | int n = s.size(); 6 | for(int i = 0; i < n; ++i) 7 | rpos[s[i] - 'a'] = i; 8 | int st = 0; 9 | vector ans; 10 | while(st < n) { 11 | int len = 1, en = rpos[s[st]-'a']; 12 | while(st < en) { 13 | ++st, ++len; 14 | en = max(en, rpos[s[st]-'a']); 15 | } 16 | ans.push_back(len); 17 | ++st; 18 | } 19 | return ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Patching Array.cpp: -------------------------------------------------------------------------------- 1 | using ll = long long; 2 | class Solution { 3 | public: 4 | int minPatches(vector& nums, int n) { 5 | int i = 0; 6 | ll sum = 0; 7 | int patch = 0; 8 | while(i < nums.size() && sum < n) { 9 | if(nums[i] <= sum+1) { 10 | sum += nums[i]; ++i; 11 | } else { 12 | sum += sum+1; 13 | ++patch; 14 | } 15 | } 16 | while(sum < n) ++patch, sum+= sum+1; 17 | return patch; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Perfect Squares.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numSquares(int n) { 4 | vector dp(n + 1); 5 | dp[0] = 0; 6 | for(int i = 1; i <= n; ++i) { 7 | dp[i] = n; 8 | for(int j = 1; j * j <= i; ++j) 9 | dp[i] = min(dp[i], dp[i-j*j] + 1); 10 | } 11 | return dp[n]; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Permutation in String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool checkInclusion(string a, string b) { 4 | vector fa(26, 0), fb(26, 0); 5 | int n = a.length(), m = b.length(); 6 | if(m < n) return false; 7 | for(int i = 0; i < n-1; ++i) 8 | fa[a[i]-'a']++, fb[b[i]-'a']++; 9 | 10 | fa[a[n-1]-'a']++; 11 | for(int i = n-1; i < m; ++i) { 12 | fb[b[i]-'a']++; 13 | if(fb == fa) return true; 14 | fb[b[i+1-n]-'a']--; 15 | } 16 | return false; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Populating Next Right Pointers in Each Node II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | Node* connect(Node* root) { 4 | if(!root) { 5 | return NULL; 6 | } 7 | queue q; 8 | q.push(root); 9 | q.push(NULL); 10 | while(q.size()!=1) { 11 | Node *temp = q.front(); 12 | q.pop(); 13 | if(!temp) { 14 | q.push(NULL); 15 | }else { 16 | temp->next = q.front(); 17 | if(temp->left) q.push(temp->left); 18 | if(temp->right) q.push(temp->right); 19 | } 20 | } 21 | return root; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Power of Two.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPowerOfTwo(int n) { 4 | return n > 0 && !(n&(n-1)); 5 | } 6 | }; 7 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Product of Array Except Self.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector productExceptSelf(vector& nums) { 4 | int n = nums.size(); 5 | vector ans(n); 6 | ans[0] = 1; 7 | for(int i = 1; i < n; ++i) 8 | ans[i] = ans[i-1] * nums[i-1]; 9 | int suf = 1; 10 | for(int i = n-1; i >= 0; --i) { 11 | ans[i] *= suf; 12 | suf *= nums[i]; 13 | } 14 | return ans; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Range Addition II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxCount(int m, int n, vector>& ops) { 4 | int mnR = m, mnC= n; 5 | // everything is max until min xi, min yi 6 | for(auto &i : ops) mnR = min(mnR, i[0]), mnC = min(mnC, i[1]); 7 | return mnR * mnC; 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Range Sum Query - Immutable.cpp: -------------------------------------------------------------------------------- 1 | class NumArray { 2 | public: 3 | vector pre; 4 | NumArray(vector& nums) { 5 | pre.resize(nums.size() + 1); 6 | pre[0] = 0; 7 | for(int i = 1; i<= nums.size(); ++i) 8 | pre[i] = pre[i-1] + nums[i-1]; 9 | } 10 | 11 | int sumRange(int left, int right) { 12 | return pre[right+1] - pre[left]; 13 | } 14 | }; 15 | 16 | /** 17 | * Your NumArray object will be instantiated and called as such: 18 | * NumArray* obj = new NumArray(nums); 19 | * int param_1 = obj->sumRange(left,right); 20 | */ 21 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Range Sum Query 2D - Immutable.cpp: -------------------------------------------------------------------------------- 1 | class NumMatrix { 2 | vector> s; 3 | public: 4 | NumMatrix(vector>& mat) { 5 | int n = mat.size(), m = mat[0].size(); 6 | s = vector>(n+1, vector(m+1)); 7 | for(int r = 1; r <= n; ++r) 8 | for(int c = 1; c <= m; ++c) 9 | s[r][c] = s[r-1][c] + s[r][c-1] - s[r-1][c-1] + mat[r-1][c-1]; 10 | } 11 | 12 | int sumRegion(int r1, int c1, int r2, int c2) { 13 | return s[r2+1][c2+1] - s[r1][c2+1] - s[r2+1][c1] + s[r1][c1]; 14 | } 15 | }; 16 | 17 | /** 18 | * Your NumMatrix object will be instantiated and called as such: 19 | * NumMatrix* obj = new NumMatrix(matrix); 20 | * int param_1 = obj->sumRegion(row1,col1,row2,col2); 21 | */ 22 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/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 lo, int hi) { 15 | if(!root) return 0; 16 | return (root->val >= lo && root->val<=hi ? root->val : 0) + rangeSumBST(root->left, lo, hi) + rangeSumBST(root->right, lo, hi); 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Remove All Adjacent Duplicates in String II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string removeDuplicates(string a, int k) { 4 | stack> s; 5 | for(char c : a) { 6 | if(!s.empty() && s.top().first == c) { 7 | pair p = s.top(); s.pop(); 8 | p.second += 1; 9 | if(p.second < k) 10 | s.push(p); 11 | } else { 12 | s.push({c, 1}); 13 | } 14 | } 15 | a = ""; 16 | while(!s.empty()) { 17 | a += string(s.top().second, s.top().first); 18 | s.pop(); 19 | } 20 | reverse(a.begin(), a.end()); 21 | return a; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Remove Covered Intervals.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int removeCoveredIntervals(vector>& a) { 4 | int ans = a.size(); 5 | sort(a.begin(), a.end(), [](vector &p, vector &q) { 6 | if(p[0] == q[0]) 7 | return p[1] > q[1]; 8 | return p[0] < q[0]; 9 | }); 10 | int en = a[0][1]; 11 | for(int i = 1; i < a.size(); ++i) { 12 | if(a[i][1] > en) 13 | en = a[i][1]; 14 | else 15 | --ans; 16 | } 17 | return ans; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Remove Duplicates from Sorted Array II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int removeDuplicates(vector& nums) { 4 | int n = nums.size(), j = 0, count = 1, total = 0; 5 | for(int i = 1; ival == val) return removeElements(head->next, val); 16 | head->next = removeElements(head->next, val); 17 | return head; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Remove Palindromic Subsequences.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int removePalindromeSub(string s) { 4 | int i = 0, j = s.length()-1; 5 | while(i < j && s[i] == s[j]) ++i, --j; 6 | return i >= j ? 1 : 2; 7 | } 8 | }; 9 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Reverse Only Letters.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string reverseOnlyLetters(string s) { 4 | int i = 0, j = s.length()-1; 5 | while(i < j) { 6 | if(!( (s[i]>='a' && s[i] <= 'z') || (s[i]>='A' && s[i]<='Z') )) { 7 | ++i; continue; 8 | } 9 | if(!( (s[j]>='a' && s[j] <= 'z') || (s[j]>='A' && s[j]<='Z') )) { 10 | --j; continue; 11 | } 12 | swap(s[i], s[j]); 13 | ++i, --j; 14 | } 15 | return s; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Reverse String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void reverseString(vector& s) { 4 | reverse(s.begin(), s.end()); 5 | } 6 | }; 7 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Reverse Words in a String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string reverseWords(string s) { 4 | string res = ""; 5 | string word = ""; 6 | for(int i = s.length()-1; i >= 0; --i){ 7 | if(s[i] == ' ') { 8 | if(word!="") { 9 | reverse(word.begin(), word.end()); 10 | res += (res == ""? word : " " + word); 11 | } 12 | word = ""; 13 | } else { 14 | word += s[i]; 15 | } 16 | } 17 | if(word!="") { 18 | reverse(word.begin(), word.end()); 19 | res += (res == ""? word : " " + word); 20 | } 21 | return res; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Richest Customer Wealth.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maximumWealth(vector>& accounts) { 4 | int ans = 0; 5 | for(auto &i : accounts) 6 | ans = max(ans, accumulate(i.begin(), i.end(), 0)); 7 | return ans; 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Rotate Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void rotate(vector& nums, int k) { 4 | k = nums.size() - (k%nums.size()); 5 | std::rotate(nums.begin(), nums.begin() + k, nums.end()); 6 | } 7 | }; 8 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Running Sum of 1d Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector runningSum(vector& nums) { 4 | for(int i = 1; i < nums.size(); ++i) 5 | nums[i] += nums[i-1]; 6 | return nums; 7 | } 8 | }; 9 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Score of Parentheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int scoreOfParentheses(string a) { 4 | int ans = 0, cur = 0; 5 | stack s; 6 | for(char c : a) { 7 | if(c == '(') { 8 | s.push(cur); 9 | cur = 0; 10 | } 11 | else { 12 | cur = s.top() + max(2*cur, 1); 13 | s.pop(); 14 | } 15 | } 16 | return cur; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Search Insert Position.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int searchInsert(vector& nums, int target) { 4 | int lo = 0, hi = nums.size()-1; 5 | while(lo <= hi) { 6 | int mid = (lo+hi)/2; 7 | if(nums[mid]>=target) hi = mid-1; 8 | else lo = mid+1; 9 | } 10 | return lo; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Search a 2D Matrix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool searchMatrix(vector>& a, int k) { 4 | int m = a.size(), n = a[0].size(); 5 | int lo = 0, hi = m*n-1; 6 | while(lo <= hi) { 7 | int mid = (lo + hi)/2; 8 | if(a[mid/n][mid%n] < k) 9 | lo = mid+1; 10 | else 11 | hi = mid-1; 12 | } 13 | ++hi; 14 | return hi < m*n && a[hi/n][hi%n] == k; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Search in Rotated Sorted Array II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool search(vector& nums, int target) { 4 | return find(nums.begin(), nums.end(), target) != nums.end(); 5 | } 6 | }; 7 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/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 | if(!root) return nullptr; 16 | if(root->val == val) return root; 17 | if(root->val < val) return searchBST(root->right, val); 18 | return searchBST(root->left, val); 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Sequential Digits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector sequentialDigits(int low, int high) { 4 | vector res; 5 | for(int s = 1; s <= 9; ++s) { 6 | int cur = 0; 7 | for(int d = s; d <= 9; ++d) { 8 | cur = cur*10 + d; 9 | if(cur >= low && cur <= high) 10 | res.push_back(cur); 11 | } 12 | } 13 | sort(res.begin(), res.end()); 14 | return res; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Shifting Letters.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string shiftingLetters(string s, vector& a) { 4 | int n = a.size(); 5 | for(int i = n-2; i>=0; --i) a[i] = (a[i+1]%26 + a[i])%26; 6 | for(int i = 0; i < n; ++i) { 7 | s[i] ='a' + (s[i]-'a'+ a[i]%26)%26; 8 | } 9 | return s; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Single Element in a Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int singleNonDuplicate(vector& nums) { 4 | int lo = 0, hi = nums.size()-1; 5 | if(lo == hi) return nums[lo]; 6 | while(lo <= hi) { 7 | int mid = (lo + hi)/2; 8 | bool can; 9 | if(mid&1) can = nums[mid] != nums[mid-1]; 10 | else can = nums[mid]!= nums[mid+1]; 11 | 12 | if(can) hi = mid-1; 13 | else lo = mid + 1; 14 | } 15 | return nums[hi+1]; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Single Number III.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector singleNumber(vector& nums) { 4 | unsigned int allxor = accumulate(nums.begin(), nums.end(), 0ll, [](unsigned int u,int v){ 5 | return u^v; 6 | }); 7 | int bit = allxor & -allxor; 8 | int xor1 = 0; 9 | for(int i : nums) { 10 | if(i&bit) xor1 ^= i; 11 | } 12 | return {xor1, (int)(allxor ^ xor1)}; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Single Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int singleNumber(vector& nums) { 4 | return accumulate(nums.begin(), nums.end(), 0, [](int a, int b) { 5 | return a^b; 6 | }); 7 | } 8 | }; 9 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Slowest Key.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | char slowestKey(vector& a, string s) { 4 | int t = a[0]; 5 | char c = s[0]; 6 | for(int i = 1; i < s.length(); ++i) { 7 | if(a[i] - a[i-1] > t) { 8 | t = a[i] - a[i-1]; 9 | c = s[i]; 10 | } else if(a[i]-a[i-1] == t) { 11 | c = max(c, s[i]); 12 | } 13 | } 14 | return c; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Smallest Integer Divisible by K.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int smallestRepunitDivByK(int k) { 4 | int len = 1, r = 1%k; 5 | unordered_set rem; 6 | rem.insert(r); 7 | while(r != 0) { 8 | r = (r*10 + 1)%k; 9 | if(rem.find(r) != rem.end()) return -1; 10 | rem.insert(r); 11 | ++len; 12 | } 13 | return len; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Smallest String With A Given Numeric Value.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string getSmallestString(int n, int k) { 4 | string res(n , 'a'); 5 | k-=n; 6 | for(int i = n-1; i>=0 && k>0; --i) { 7 | res[i] += min(25 , k); 8 | k-= min(25 , k); 9 | } 10 | return res; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Sort Array By Parity II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector sortArrayByParityII(vector& nums) { 4 | int ptr[2] = {0, 1}; 5 | for(int i = 0; i < nums.size(); ++i) { 6 | if(nums[i]%2 == i%2) continue; 7 | int j = 1-(i%2); 8 | while(nums[ptr[j]]%2 != i%2) ptr[j]+=2; 9 | swap(nums[i], nums[ptr[j]]); 10 | } 11 | return nums; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Sort Array By Parity.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector sortArrayByParity(vector& nums) { 4 | int i = 0, j = nums.size()-1; 5 | while(i <= j) { 6 | if((nums[i]&1) == 0) { 7 | ++i; 8 | continue; 9 | } 10 | if(nums[j]&1) { 11 | --j; 12 | continue; 13 | } 14 | swap(nums[i], nums[j]); 15 | ++i; --j; 16 | } 17 | return nums; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Sort Characters By Frequency.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string frequencySort(string s) { 4 | unordered_map frequency; 5 | for(char c : s) frequency[c]++; 6 | 7 | auto compare = [&](char a, char b) -> bool { 8 | if(frequency[a] == frequency[b]) return a < b; 9 | return frequency[a] >= frequency[b]; 10 | }; 11 | 12 | sort(s.begin(), s.end(), compare); 13 | return s; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Sort Colors.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void sortColors(vector& nums) { 4 | int zero = -1; 5 | int two = nums.size(); 6 | int i = 0; 7 | while(i < two) { 8 | if(nums[i] == 0) { 9 | ++zero; 10 | swap(nums[zero], nums[i]); 11 | ++i; 12 | } 13 | else if(nums[i] == 2) { 14 | --two; 15 | swap(nums[two], nums[i]); 16 | } 17 | else ++i; 18 | } 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Spiral Matrix II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> generateMatrix(int n) { 4 | vector> a(n, vector (n)); 5 | int k = 1, r1 = 0, r2 = n-1, c1 = 0, c2 = n-1; 6 | while(r1 <= r2 && c1 <= c2) { 7 | for(int c = c1; c <= c2; ++c) 8 | a[r1][c] = k++; 9 | for(int r = r1+1; r <= r2; ++r) 10 | a[r][c2] = k++; 11 | for(int c = c2-1; c>=c1; --c) 12 | a[r2][c] = k++; 13 | for(int r = r2-1; r > r1; --r) 14 | a[r][c1] = k++; 15 | ++c1; --c2; 16 | ++r1; --r2; 17 | } 18 | return a; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Split Array Largest Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int required(vector &nums, int mx) { 4 | int req = 0; 5 | int i = 0, n = nums.size(); 6 | while(i < n) { 7 | if(nums[i] > mx) return INT_MAX; 8 | ++req; 9 | int cur = 0; 10 | while(i < n && cur + nums[i] <= mx) 11 | cur += nums[i++]; 12 | } 13 | return req; 14 | } 15 | int splitArray(vector& nums, int m) { 16 | int lo = 0, hi = accumulate(nums.begin(), nums.end(), 0); 17 | while(lo <= hi) { 18 | int mid = (lo + hi)/2; 19 | if(required(nums, mid) <= m) 20 | hi = mid-1; 21 | else 22 | lo = mid+1; 23 | } 24 | return hi+1; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Stone Game IV.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool winnerSquareGame(int n) { 4 | vector dp(n+1, false); 5 | dp[0] = false; 6 | for(int i = 1; i <= n; ++i) { 7 | for(int j = 1; j*j <= i; ++j) { 8 | if(dp[i-j*j] == false) { 9 | dp[i] = true; 10 | break; 11 | } 12 | } 13 | } 14 | return dp[n]; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Stone Game.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> dp; 4 | int rec(int i , int j, vector &a) { 5 | if(i > j) 6 | return 0; 7 | int &ret = dp[i][j]; 8 | if(ret != -1) 9 | return ret; 10 | ret = max(a[i] - rec(i+1, j, a) , a[j] - rec(i, j-1, a)); 11 | return ret; 12 | } 13 | bool stoneGame(vector& piles) { 14 | int n = piles.size(); 15 | dp.resize(n , vector(n, -1)); 16 | int ans = rec(0, n-1, piles); 17 | return ans > 0; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/String to Integer (atoi).cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int myAtoi(string s) { 4 | bool neg = false; 5 | long long ans = 0; 6 | int i = 0, n = s.length(); 7 | 8 | while(i < n && s[i] == ' ') ++i; 9 | if(s[i] == '+' || s[i] == '-') { 10 | neg = (s[i] == '-'); 11 | ++i; 12 | } 13 | 14 | while(i '9') break; 16 | ans = 10*ans + (neg?-1:1) * (s[i]-'0'); 17 | ans = min(ans, (long long)INT_MAX); 18 | ans = max(ans, (long long)INT_MIN); 19 | i++; 20 | } 21 | 22 | return ans; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Subarray Sum Equals K.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int subarraySum(vector& nums, int k) { 4 | unordered_map seen = {{0, 1}}; 5 | int count = 0, sum = 0; 6 | for (auto n: nums) { 7 | sum += n; 8 | count += seen[sum - k]; 9 | seen[sum]++; 10 | } 11 | return count; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Subsets II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> subsetsWithDup(vector& a) { 4 | sort(a.begin() , a.end()); 5 | int n = a.size(); 6 | vector> powerSet(1<(); 8 | for(int m = 1; m < (1<left) + sumOfLeftLeaves(root->right); 17 | if(root->left && !root->left->left && !root->left->right) ans += root->left->val; 18 | return ans; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Sum of Root To Leaf Binary Numbers.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 dfs(TreeNode *root, int cur) { 15 | if(!root) return 0; 16 | cur = (cur<<1) + root->val; 17 | if(!root->left && !root->right) return cur; 18 | return dfs(root->left, cur) + dfs(root->right, cur); 19 | } 20 | int sumRootToLeaf(TreeNode* root) { 21 | return dfs(root, 0); 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Sum of Square Numbers.cpp: -------------------------------------------------------------------------------- 1 | bool judgeSquareSum(int c) { 2 | for(long long i = 0; i * i <= c; i++){ 3 | long long a = c - i * i, b = sqrt(a); 4 | 5 | if(b * b == a){ 6 | return true; 7 | } 8 | } 9 | return false; 10 | } 11 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Summary Ranges.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector summaryRanges(vector& nums) { 4 | int i = 0, n = nums.size(); 5 | vector ans; 6 | while(i < n) { 7 | int j = i+1; 8 | while(j < n && nums[j] == nums[j-1] + 1) ++j; 9 | if(j == i+1) 10 | ans.push_back(to_string(nums[i])); 11 | else 12 | ans.push_back(to_string(nums[i]) + "->" + to_string(nums[j-1])); 13 | i = j; 14 | } 15 | return ans; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/The K Weakest Rows in a Matrix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector kWeakestRows(vector>& mat, int k) { 4 | vector> a; 5 | for(int r = 0; r < mat.size(); ++r) { 6 | int c = 0; 7 | while(c < mat[r].size() && mat[r][c] == 1) ++c; 8 | a.push_back({c, r}); 9 | } 10 | sort(a.begin(), a.end()); 11 | vector res(k); 12 | for(int i = 0; i < k; ++i) 13 | res[i] = a[i].second; 14 | return res; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Top K Frequent Elements.cpp: -------------------------------------------------------------------------------- 1 | using pii = pair; 2 | class Solution { 3 | public: 4 | vector topKFrequent(vector& nums, int k) { 5 | unordered_map m; 6 | for(int i : nums) m[i]++; 7 | priority_queue, greater> pq; 8 | for(auto &i : m) 9 | if(pq.size() < k) pq.push({i.second, i.first}); 10 | else if(pq.top().first < i.second) pq.pop(), pq.push({i.second, i.first}); 11 | vector res; 12 | while(!pq.empty()) 13 | res.push_back(pq.top().second), pq.pop(); 14 | return res; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Transpose Matrix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> transpose(vector>& matrix) { 4 | int n = matrix.size(), m = matrix[0].size(); 5 | vector> res(m, vector (n, 0)); 6 | for(int i = 0; i < n; ++i) { 7 | for(int j = 0; j < m; ++j) { 8 | res[j][i] = matrix[i][j]; 9 | } 10 | } 11 | return res; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Triangle.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minimumTotal(vector>& triangle) { 4 | for(int i = triangle.size()-2; i>=0; --i) { 5 | for(int j = 0; j <=i ;++j) 6 | triangle[i][j]+= min(triangle[i+1][j] , triangle[i+1][j+1]); 7 | } 8 | return triangle[0][0]; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Two City Scheduling.cpp: -------------------------------------------------------------------------------- 1 | template ostream & operator << (ostream &os, const vector &v) { 2 | os << "[ "; 3 | for(T a : v) os << a << ", "; 4 | os << "]\n"; 5 | return os; 6 | } 7 | class Solution { 8 | public: 9 | int twoCitySchedCost(vector>& costs) { 10 | int n = costs.size()/2; 11 | vector prev(n+1, 1e9); 12 | prev[0] = 0; 13 | for(auto &cost: costs) { 14 | vector cur(n+1); 15 | cur[0] = prev[0] + cost[1]; 16 | for(int i = 1; i <= n; ++i) { 17 | cur[i] = min(prev[i] + cost[1], prev[i-1] + cost[0]); 18 | } 19 | // cout << cur; 20 | swap(cur, prev); 21 | } 22 | return prev[n]; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Two Sum II - Input Array Is Sorted.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector twoSum(vector& numbers, int target) { 4 | for(int i = 0; i < numbers.size()-1; ++i) { 5 | int x = target - numbers[i]; 6 | int hi = numbers.size()-1 , lo = i+1; 7 | while(lo<=hi) { 8 | int mid = (hi+lo)/2; 9 | if(numbers[mid] == x) { 10 | vector v{i+1 , mid+1}; 11 | return v; 12 | } else if(numbers[mid] > x) hi = mid-1; 13 | else lo = mid+1; 14 | } 15 | } 16 | vector v; 17 | return v; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Two Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector twoSum(vector& a, int k) { 4 | set< pair> s; 5 | int n = a.size(); 6 | for(int i = 0; i < n; ++i) { 7 | s.insert({a[i], i}); 8 | } 9 | for(int i = 0; i < n; ++i) { 10 | s.erase({a[i], i}); 11 | auto it = s.lower_bound({k - a[i] , -1}); 12 | if(it != s.end() && (*it).first == k-a[i]) { 13 | return {i, (*it).second}; 14 | } 15 | s.insert({a[i], i}); 16 | } 17 | return {-1,-1}; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Unique Binary Search Trees.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numTrees(int n) { 4 | vector trees(n+1); 5 | trees[0] = 1; 6 | for(int i = 1; i <= n; ++i) { 7 | for(int j = 0; j < i; ++j) { 8 | trees[i] += trees[j] * trees[i-1-j]; 9 | } 10 | } 11 | return trees[n]; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Unique Email Addresses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numUniqueEmails(vector& emails) { 4 | unordered_set s; 5 | for(string &email : emails) { 6 | auto idx = find(email.begin(), email.end(), '@') - email.begin(); 7 | string res = ""; 8 | for(int i = 0 ; i < idx; ++i) 9 | if(email[i] == '+') break; 10 | else if(email[i] != '.') res += email[i]; 11 | res += email.substr(idx); 12 | s.insert(res); 13 | } 14 | 15 | return s.size(); 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Unique Paths.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int ncr(int n, int r) { 4 | long long ans = 1; 5 | int tn = n - r; 6 | while(r > 0 || n > tn) { 7 | if(r> 0 && ans % r == 0) ans/= r--; 8 | else ans *= n--; 9 | } 10 | return ans; 11 | } 12 | int uniquePaths(int m, int n) { 13 | return ncr(m+n-2, m-1); 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Valid Mountain Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool validMountainArray(vector& arr) { 4 | int i = 0, n = arr.size(); 5 | if(n < 3) return false; 6 | while(i < n-1 && arr[i] < arr[i+1]) ++i; 7 | if(i == 0 || i == n-1) return false; 8 | while(i < n-1 && arr[i] > arr[i+1]) ++i; 9 | return i == n-1; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Valid Palindrome II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPalin(string &s, int i, int j) { 4 | while(i < j && s[i] == s[j]) ++i, --j; 5 | return i >= j; 6 | } 7 | bool validPalindrome(string s) { 8 | int i = 0, j = s.length()-1; 9 | while(i < j) { 10 | if(s[i] == s[j]) 11 | ++i, --j; 12 | else return isPalin(s, i+1, j) || isPalin(s, i, j-1); 13 | } 14 | return true; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Valid Parentheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isValid(string s) { 4 | stack st; 5 | for(char c : s) { 6 | if(c == '(' || c == '[' || c == '{') 7 | st.push(c); 8 | else if(c == ')') { 9 | if(st.empty() || st.top() != '(') return false; 10 | else st.pop(); 11 | } else if(c == ']') { 12 | if(st.empty() || st.top() != '[') return false; 13 | else st.pop(); 14 | } else { 15 | if(st.empty() || st.top() != '{') return false; 16 | else st.pop(); 17 | } 18 | } 19 | return st.empty(); 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Valid Triangle Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int triangleNumber(vector& a) { 4 | int n = a.size(); 5 | sort(a.begin() , a.end()); 6 | int nz = n - count(a.begin() , a.end() , 0); 7 | int ans = (nz * (nz-1) * (nz-2) )/6; 8 | for(int i = 0; i < n; ++i) { 9 | for(int j = i+1; j+1 < n; ++j) { 10 | if(a[i] == 0 || a[j] == 0) continue; 11 | int id = lower_bound(a.begin() , a.end() , a[i] + a[j]) - a.begin(); 12 | // cout << i << " " << j << " " << id << endl; 13 | ans -= n-id; 14 | } 15 | } 16 | return ans; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Validate Stack Sequences.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool validateStackSequences(vector& pushed, vector& popped) { 4 | stack s; 5 | int i = 0, j = 0 , n = pushed.size(); 6 | while(i < n && j < n) { 7 | if(!s.empty() && popped[j] == s.top()) { 8 | ++j; 9 | s.pop(); 10 | } else { 11 | s.push(pushed[i]); 12 | ++i; 13 | } 14 | } 15 | while(j < n) { 16 | if(s.top() != popped[j]) return false; 17 | s.pop(); ++j; 18 | } 19 | return true; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Leetcode Daily Challenges/Word Pattern.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool wordPattern(string pattern, string s) { 4 | vector m(26, ""); 5 | int i = 0, n = s.length(); 6 | unordered_map wcMap; 7 | for(char c : pattern) { 8 | string w = ""; 9 | while(i < n && s[i] != ' ') 10 | w += s[i++]; 11 | if(w == "") return false; 12 | if((m[c-'a']!="" && m[c-'a'] != w) || (wcMap.count(w) > 0 && wcMap[w] != c)) 13 | return false; 14 | m[c-'a'] = w; 15 | wcMap[w] = c; 16 | ++i; 17 | } 18 | return i >= n; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Competitive-Programming 2 | CP Templates, Solutions, Standard Problems 3 | 4 | Profiles : 5 | - linkedin - https://www.linkedin.com/in/notabhishek/ 6 | - codeforces - https://codeforces.com/profile/devil_within 7 | - codechef - https://www.codechef.com/users/not_abhishek 8 | - hackerearth - https://www.hackerearth.com/@notabhishek 9 | - leetcode - https://leetcode.com/notabhishek/ 10 | - hackerrank - https://www.hackerrank.com/notabhishek 11 | - cses - https://cses.fi/user/22538 12 | -------------------------------------------------------------------------------- /Standard FFT Problems/readme.txt: -------------------------------------------------------------------------------- 1 | standard FFT Problems 2 | -------------------------------------------------------------------------------- /Standard SegTree Problems/readme.txt: -------------------------------------------------------------------------------- 1 | Standard Segment Tree Problems 2 | -------------------------------------------------------------------------------- /Templates/DSU.cpp: -------------------------------------------------------------------------------- 1 | const int NAX = 3e5 + 100; 2 | int par[NAX]; 3 | int siz[NAX]; 4 | 5 | void init(int n) { 6 | for(int i = 1; i <= n; ++i) { 7 | par[i] = i; 8 | siz[i] = 1; 9 | } 10 | } 11 | 12 | int getp(int u) { 13 | if(par[u] == u) 14 | return par[u]; 15 | return par[u] = getp(par[u]); 16 | } 17 | 18 | void uni(int x ,int y) { 19 | int u = getp(x); 20 | int v = getp(y); 21 | if(u == v) 22 | return; 23 | if(siz[u] > siz[v]) 24 | swap(u , v); 25 | siz[v] += siz[u]; 26 | par[u] = v; 27 | } 28 | 29 | -------------------------------------------------------------------------------- /Templates/readme.txt: -------------------------------------------------------------------------------- 1 | My Templates 2 | --------------------------------------------------------------------------------