Skip to content

IamConstantine/LeetCodeFiddle

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Build Status

LeetCodeFiddle

Solutions to LeetCode problems in Scala

Hints:

Dynamic Programming

  1. Unique Paths - Use the dp array to solve this in O(mn) complexity. Instantiate first row and first column with 1 as its a known valid path to m.n. There's an intuitive recursive + memoisation solution as well.
  2. String Two Digit Decoding - The DP array solution. Each non zero is a 1 ie dp[i] = dp[i-1] and each two digits >=10 is dp[i] += dp[i-2].
  3. Word Break - DP Recursion + memoisation
  4. House Robber - Calculate max(i + i-2, i-1).
  5. Long Increasing Sequence - An N^2 algo to compute the seq length for every ith value.
  6. Longest Common Subsequence - use bottom up on a dp[text1+1][text2+1] array. Refer the solution section for more details.
  7. House Robber II - compute max of house_robber(1, N) and house_robber(0, N-1).
  8. Stone Game IV - use dfs with memo or dp to calculate for each value of n from 1 to n + 1.
  9. Count Delivery Orders - Use top-down DP with memo to solve the problem using permutations. 10.Ones and Zeroes - Use DP(m,n,idx) with list of counters.

Divide and Conquer

  1. Search in Rotated Array - Use Binary search approach to solve in O(log n). Find the mid and check if right is sorted first ie compare l and mid. Binary search is called a decrease and conquer problem instead of divide and conquer.
  2. Find Min in Rotated Array - Use Binary Search to find min in search space.
  3. Sort Linked List - Use merge sort.
  4. Search in Rotated Array II - Use Binary search with code to handle duplicates.
  5. Split Array Largest Sum - Use binary search on max of nums to sum of nums space.

Backtracking

  1. Combination Sum - Find all combinations for the given sum. Nothing to memoise here. You can use one node multiple times in the path to find the combination. But you cannot use your parent node once you have gone down the level.
  2. Word Search - Intuitive solution using visited matrix and traverse all 3 directions from one cell approach.
  3. Word Search II - Use Trie of all the words and then traverse the board like Word Search Problem. We would need to pop leaves when match is met to avoid exploration of visited trie nodes.
  4. Brace Expansion - use backtracking to find all the combinations.
  5. Robot Room Cleaner - visited all directions but always only use turnRight().

Strings

  1. Group Anagrams - can define group key using sorted strings(O(NKlogK)) or character count(0(NK)) approach
  2. String Minimum Window - use length of t and l and r ptrs for window to solve this in O(2S)
  3. Validate Palindrome - Easy problem solved using a l and r pointer.
  4. Is Anagram ? - Use Hashset
  5. String Codec - use 4 byte chunked encoding for storing length of each string in list.
  6. Group Shifted Strings - create a group key based on the shifts.
  7. Find Anagrams - use two counters - one for p and another to track what has been seen till now and update accordingly.
  8. Check Inclusion - Use Sliding window with counter.
  9. K length Substring No Repeats - use sliding window.
  10. Strobogrammatic Number - II - use level order to find the required combinations.
  11. Character Replacement - use a sliding window to figure out the valid char set.
  12. Count Pallindromic Substrings - use an expand around center approach.
  13. Score of Parantheses - count cores ie ().
  14. Minimize result using parantheses - use a precalculated list of combinations for each number and then pair up every combination.
  15. Total Appeal of String - use previously computed output to find the current value.
  16. Number of matching Subsequence - use next letter pointers.

Array

  1. Spiral Order - Simple problem - The time spent is to figure out the boundaries, and edge cases(when right = left or up = down).
  2. Merge Intervals - Sort the intervals in nlogn and then just do a linear comparison.
  3. Insert Interval - As the list is already sorted and has non overlapping intervals, its an easy problem which is similar to Merge Intervals
  4. Set Zeroes - Intuitive solution using additional set for row and column indices is easy. The no additional space solution is a bit tricky and read the code comments to understand that.
  5. Longest Common Subsequence - N iterator and do an inner loop only when you find the head of a sequence i.e curr - 1 not in nums_set. We use set for O(1) lookup and also to eliminate duplicates
  6. Product Except Self - Build an array with left product and then calculate right product and the output array.
  7. Non-Overlapping Intervals - Similiar to merge intervals which needs sorting. In this while merging, just do a count instead.
  8. Top K Frequent Elements - Use Quick-select to partition the array and move all k element to the right.
  9. Max Distance to Closest - Use a simple n algorithm to find mid between two allocated seats.
  10. Meeting Rooms - sort and then compare i end with i +1 start.
  11. Meeting Rooms II - sort by start time and use heap on end time to get the no of rooms required or separate start and end ts and work on that using two pointers.
  12. Can Place Flowers - start from imaginary prev -2 and find no of plots which can be used between two flowers.
  13. Monotonic Array - set inc and dec to True and then start the loop to unset the required flags based on the order of growth.
  14. Koko Eating Bananas - use binary search to find the required rate in 1, max(piles) search space.
  15. Gas Station - take two counters. Total has all deficit : gas - cost and curr tracks consumption from a good starting point.
  16. Sequential Numbers - Use a sliding window on '123456789' string.
  17. Largest Rectangle in Histogram - use stack to push elements in increasing order and then pop and calculate the area for each popped element.
  18. Rotate Array - Reverse whole list and then 0,k-1 and k, end.
  19. 4 Sum ii - run a loop on k//2 lists to generate counter and then run on the remaining to find the complement.
  20. Find Max Length of Zeros and Ones in array - a very high IQ implementation using map to track the count of 0s and 1s and track max length.
  21. Subarray Sum - use map to store cumulative and the no of occurences.
  22. Subsets - Use cascading to solve in N * 2 ^ N.
  23. Remove K Digits - Use a stack to compare left and curr digit.
  24. Champagne Tower - Use 2D array to track progress of glasses.
  25. [Campus Bikes](https://leetcode.com/problems/campus-bikes] - Use bucketing to sort out all distance pairs and then pick first N workers pairs.
  26. Max Frequency Stack - Two approaches: One can be done using Max Heap with a triplet of (freq, index, val) and another one can done using freq group and a max variable.
  27. Increasing Triplets - use a loop to find a first and second.
  28. Search 2D Matrix - start from bottom left and decrement row and increment column until we find the target.
  29. Find Duplicates Number - Use Floyd's Cycle Detection Algorithm.
  30. Next Permutation - A single pass approach by reversing some part of the array.
  31. Minimize Sum of Products of Two Arrays - Sort two arrays in different orders and then perform sum of products.
  32. 132 Pattern - use stack and min to track the valid tuples.

Linked List

  1. Detect Loop - Floyd's Cycle Detection Algorithm.
  2. Reorder List - first and last ptrs on a list to traverse and merge them.
  3. Reverse LL - n iteration solution.

Greedy

  1. Can Jump - Simple bottom up solution using Greedy. Just use the lastPos pointer to solve the local optima. This problem can be solved using DP as well but the solution is worse ie O(n^2)
  2. Remove Covered Interval - sort start asc and end desc and then use only end time to figure out actual count.
  3. Validate Stack Sequences - use a greedy approach to start popping once u find a match.
  4. Remove Duplicate Characters - use greedy with stack approach.
  5. Min Domino Rotations - Use greedy approach on an any arbitrary index.
  6. Broken Calculator - Greedily divide the target to reach near the startValue and then use addition to reach the startValue.
  7. Min Deletions To Beautiful Array - greedily create another array with elligible elements.

Tree

  1. Same Tree - Simple preorder traversal and equality check
  2. Max Depth - easy tree traversal and sum. This can be solved either using BFS iteration using stack or using recursion
  3. Validate BST - Medium question to find a simple trick. Each node in the tree should greater than max of its left and smaller than min of its right.
  4. Level Order Tree - Easy Question which is solved using a Queue
  5. Contruct Binary Tree - Solved using inorder map(value, index),incrementing preorder index and a l and r for tracking size of subtree
  6. Tree Max Sum Path - a hard question solved within half an hour :). Find the max at each node by comparing current node, max of left and max of right.
  7. Kth Smallest Element in BST - use inorder traversal iterative.
  8. Valid Tree - A Tree has only V-1 edges. So check this and if it passes, then check if all nodes are connected. No need to check if graph has cycles because connected graph with cycle should have more than n - 1 edges.
  9. Is Subtree - Easy impl using find and isSame methods but its O(N * M). Use Merkel Tree for O(N + M) solution.
  10. Least Common Ancestor BST - Return the parent which caused for p and q.
  11. Least Common Ancestor Binary Tree - count number of matches from current + left + right>=2. If it matches this condition, the curr node is lca.
  12. Find Median in Data Stream - It can be solved using Heap or AVL. Two Heap solution is relatively easy. Use a maxheap for lower half and minheap for upper half and then the median elements can be accessed at the root.
  13. Word Dictionary - Use Trie to solve for defined words and for searches with dots use recursion.
  14. Nearest Right Node - Use BFS to track levels and then return first node after search node in the Q.
  15. Longest Common Prefix - use Trie to solve this.
  16. Max Xor Number - Use Bit Trie to find best xor pair for a number.
  17. Width Of Tree - Use BFS or DFS.
  18. Encode N-ary tree - use BFS to encode the n-ary tree where left child of binary tree would LL of all its children and right would be its siblings.
  19. Largest BST Subtree - use inorder traversal to find valid Binary search tree along with its length.
  20. Upside Down Binary Tree - just use a while loop and swap places.

Graph

  1. Clone Graph - Can use BFS to traverse each node and get all the neighbours and a map to store the new nodes as keys.
  2. Number of Islands - a solution using DFS/BFS with set. It can also be solved using Union Find.
  3. Connected Components - Use BFS/DFS to traverse each connected component.
  4. Pacific Atlantic Water Flows - use dfs to traverse all edges and individually compute visited for pacific and atlantic edges. The just perform an intersection at the end.
  5. Course Schedule - Use DFS to find if there is a cycle.
  6. Earliest Acquaintance - Sort on logtime and then use Union Find to reduce groups.
  7. Count Ships in Sea - Use divide and conquer to break the search space into 4 quads.
  8. Word Ladder - use BFS to traverse all levels.
  9. Alien Dictionary - use topological sort.
  10. Shortest Path to traverse all nodes - use dfs with visited bitmap.
  11. Maximum Minimum in Path - We will use a max heap to always traverse to max yielding path.
  12. Min Cost to connect all points - Use any MST algorithm.
  13. Smallest string with swaps - can be done using dfs by considering each swap pair as edges of graph.
  14. Evaluate Division - solved using graph where equations can be used to define the edges and value as cost.

Bit Manipulation

  1. Reverse BIts for 32 bit unsigned number - use bitwise operators to mask and shift the input
  2. Count Set Bits - use mask and shift
  3. Bitwise Sum - Read the solution section for proper understanding of the xor and and operations in the computation.
  4. Largest And Combination - find the max number of elements set any bit position.

Maths

  1. Count Latice Points - use distance formula to find all the points that lie within the radius of a circle.

About

Solutions to LeetCode Problems

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published