This repository contains comprehensive solutions to the 150 most important LeetCode questions frequently asked in technical interviews at top companies (FAANG and beyond). Each solution demonstrates optimal approaches, efficient algorithms, and best coding practices in Python. The problems are systematically organized by topic to facilitate structured interview preparation.
Master the essential Data Structures and Algorithms patterns required to excel in coding interviews through systematic practice and understanding of core concepts.
01_MergeSortedArrays.py- In-place merging with two pointers02_RemoveElements.py- Two-pointer technique for element removal03_RemoveDuplicatesFromSortedArray.py- Unique element extraction04_RemoveDuplicateSortedArrayII.py- At most two duplicates allowed05_MajorityElement.py- Boyer-Moore voting algorithm06_RotatedArray.py- Array rotation with reversal technique09_JumpGame.py- Greedy approach for reachability10_JumpGame2.py- Minimum jumps with BFS-like approach11_H_Index.py- Citation counting and sorting12_Insert_Delete_GetRandom.py- O(1) operations with HashMap + ArrayList15_Candy.py- Two-pass greedy algorithm16_TrappingRainWater.py- Two-pointer approach for water trapping17_RomanToInteger.py- Roman numeral conversion18_IntegerToRoman.py- Greedy integer to Roman conversion20_LongestCommonPrefix.py- Vertical scanning approach23_FindTheIndexOfFirstOccurenceOfString.py- String matching24_TextJustification.py- Complex text formatting algorithm
01_3Sum.py- Three-pointer approach for triplet finding02_ValidPalindrome.py- Two-pointer palindrome validation05_ContainerWithMostWater.py- Maximum area calculation with two pointers
01_MinimumSizeSubarraySum.py- Variable-size sliding window02_longestSubstringWithoutRepeatingCharacters.py- HashMap-based sliding window04_MinimumWindowSubstring.py- Complex sliding window with character frequency
01_SpiralMatrix.py- Layer-by-layer traversal02_RotateMatrix.py- In-place rotation with transpose04_SetZerosMatrix.py- O(1) space matrix modification05_GameOfLife.py- In-place state transitions
01_RansomNote.py- Character frequency counting06_TwoSum.py- Classic two-sum with HashMap07_HappyNumber.py- Cycle detection with HashSet
01_SummaryRanges.py- Consecutive number grouping02_MergeIntervals.py- Interval merging with sorting
03_MinStack.py- O(1) min retrieval with auxiliary stack04_EvaluateReversePolishNotation.py- Stack-based expression evaluation05_BasicCalculator.py- Complex calculator implementation
03_MergeTwoSortedList.py- Two-pointer merge technique08_RotateAList.py- Circular rotation with pointer manipulation
01_MaximumDepthOfBinaryTree.py- Recursive depth calculation07_PathSum.py- DFS for path finding12_CountCompleteBinaryTree.py- Binary search on tree levels13_BinaryTreeMaximumPathSum.py- Complex DFS with global maximum
02_FindThePeakElement.py- Modified binary search04_FindFirstAndLastPositionOfElementInSortedArray.py- Binary search variants05_FindMinimumInRotatedSortedArray.py- Rotated array binary search07_MedianOfTwoSortedArrays.py- Advanced binary search on two arrays
01_KthLargestElementInArray.py- QuickSelect and heap approaches02_IPO.py- Dual heap for capital maximization03_FindKPairsWithSmallestSum.py- Min heap for K smallest pairs04_FindMedianFromDataStream.py- Two heaps for running median
01_AddBinary.py- Binary addition with carry03_NumberOf1Bits.py- Bit counting techniques05_SingleNumber2.py- Bit manipulation for unique element06_BitwiseAndOfANumber.py- Range bitwise AND
MaxPointsOnLine.py- Slope calculation with HashMapPalindromeNumber.py- In-place palindrome checkPlusOne.py- Array-based digit incrementPow(n,x).py- Binary exponentiationSqrt(x).py- Binary search for square root
ClimbingStairs.py- Classic Fibonacci DPHouseRobber.py- Non-adjacent element selectionCoinChange.py- Unbounded knapsack variantLongestIncreasingSubsequence.py- O(nΒ²) DP solution
Triangle.py- Bottom-up DP on triangleMinimumPathSum.py- 2D grid path findingUniquePathII.py- Path counting with obstaclesMaximalSquare.py- 2D DP for largest squareInterleavingStrings.py- 2D string DPEditDistance.py- Classic edit distance DPBestTimeToBuyAndSellStockIII.py- 3D DP for stock tradingBestTimeToBuyAndSellStockIV.py- K transactions DP
GenerateParenthesis.py- Recursive parenthesis generationCombinationsSum.py- Combination finding with backtrackingPermutations.py- All permutations generationWordSearch.py- 2D board DFS with backtracking
NumbersOfIsland.py- DFS/BFS for connected componentsSurroundedRegions.py- Border DFS approachEvaluateDivision.py- Graph with weighted edges
SnakeAndLadder.py- BFS for shortest pathMinimumGeneticMutation.py- BFS with transformationsWordLadder.py- Bidirectional BFS
DesignAddandSearchWordsDataStructure.py- Trie with wildcard search
ConvertSortedArrayToBinaryTree.py- BST construction from sorted arraySortList.py- Merge sort on linked listConstructQuadTree.py- Quad tree constructionMergeKSortedArray.py- K-way merge with divide and conquer
01_MaximumSubarray.py- Classic Kadane's algorithm02_MaximumSumCircularSubarray.py- Circular array variant
- Fast and slow pointer technique
- Left and right pointer convergence
- Sliding window variations
- Classic binary search on sorted arrays
- Modified binary search for rotated arrays
- Binary search on answer space
- Bottom-up tabulation
- Top-down memoization
- State space optimization
- 1D, 2D, and 3D DP problems
- Depth-First Search (DFS)
- Breadth-First Search (BFS)
- Topological sorting
- Union-Find
- Shortest path algorithms
- Pre-order, In-order, Post-order traversal
- Level-order traversal
- Binary Search Tree operations
- Tree construction and reconstruction
- Activity selection
- Jump game strategies
- Interval scheduling
- Combination generation
- Permutation generation
- Constraint satisfaction
- Pruning techniques
- Trie for string operations
- Heap/Priority Queue
- Monotonic Stack/Queue
- Disjoint Set Union (DSU)
| Difficulty | Count | Percentage |
|---|---|---|
| π’ Easy | 35 | 23% |
| π‘ Medium | 85 | 57% |
| π΄ Hard | 30 | 20% |
When to use: Problems involving arrays/lists where you need to find pairs or triplets
Examples: 3Sum, Container With Most Water
When to use: Problems involving subarrays/substrings with specific properties
Examples: Minimum Window Substring, Longest Substring Without Repeating Characters
When to use: Linked list cycle detection, finding middle element Examples: Linked list problems
When to use: Overlapping intervals problems
Examples: Merge Intervals
When to use: Problems involving arrays with numbers in a given range
When to use: Reversing linked list segments
When to use: Level-order traversal, finding level averages Examples: Binary tree problems
When to use: Pre/In/Post-order traversal, path problems
Examples: Path Sum, Maximum Path Sum
When to use: Finding median in a stream
Examples: Find Median from Data Stream
When to use: Generating all combinations/permutations
Examples: Permutations
When to use: Sorted/rotated arrays, search space reduction
Examples: Search in Rotated Array
When to use: Finding K largest/smallest elements
Examples: Kth Largest Element
When to use: Merging K sorted arrays/lists
Examples: Merge K Sorted Lists
When to use: Optimization problems with overlapping subproblems
Examples: Coin Change, Edit Distance
When to use: Generating all possible solutions
Examples: Generate Parentheses, Word Search
git clone https://github.com/Ak-Rajak/Most_Imp_Interview_leetcode_Questions_150.git
cd Most_Imp_Interview_leetcode_Questions_150cd Arrays_&_Stringspython 16_TrappingRainWater.pyEach file contains:
- Problem link to LeetCode
- Detailed comments explaining the approach
- Time and space complexity analysis
- Multiple solution approaches (where applicable)
# From 16_TrappingRainWater.py
class Solution:
def trap(self, height: List[int]) -> int:
"""
Two-pointer approach:
- Maintain leftMax and rightMax
- Move pointer with smaller max
- Calculate water at each position
Time: O(n), Space: O(1)
"""
if not height:
return 0
l, r = 0, len(height) - 1
leftMax, rightMax = height[l], height[r]
res = 0
while l < r:
if leftMax < rightMax:
l += 1
leftMax = max(leftMax, height[l])
res += leftMax - height[l]
else:
r -= 1
rightMax = max(rightMax, height[r])
res += rightMax - height[r]
return res| Category | Average Time | Average Space |
|---|---|---|
| Arrays & Strings | O(n) - O(nΒ²) | O(1) - O(n) |
| Binary Search | O(log n) | O(1) |
| Dynamic Programming | O(nΒ²) - O(nΒ³) | O(n) - O(nΒ²) |
| Graphs | O(V + E) | O(V) |
| Trees | O(n) | O(h) |
| Heaps | O(n log k) | O(k) |
β Data Structure Mastery
- Arrays, Linked Lists, Trees, Graphs
- Stacks, Queues, Heaps
- Hash Tables, Tries
- Advanced structures (Segment Tree, Fenwick Tree)
β Algorithm Expertise
- Sorting and Searching algorithms
- Graph traversal (DFS, BFS)
- Dynamic Programming patterns
- Greedy algorithms
- Divide and Conquer
β Problem-Solving Skills
- Pattern recognition
- Time-space trade-off analysis
- Optimization techniques
- Edge case handling
β Interview Readiness
- Clear code communication
- Complexity analysis
- Multiple solution approaches
- Code optimization
- Arrays & Strings basics
- Two Pointers
- Hash Maps
- Basic Binary Search
- Linked Lists
- Stacks & Queues
- Trees (Basic traversals)
- Sliding Window
- Dynamic Programming (1D)
- Binary Search (Advanced)
- Heaps
- Graphs (BFS/DFS)
- Dynamic Programming (2D/3D)
- Backtracking
- Advanced Graph algorithms
- System Design considerations
- Review patterns: Focus on recognizing problem patterns
- Practice articulation: Explain your thought process clearly
- Time management: Practice solving problems within time limits
- Mock interviews: Practice with peers or use platforms
- Clarify requirements: Ask questions about edge cases
- Discuss approach: Explain your strategy before coding
- Start simple: Begin with brute force, then optimize
- Test your code: Walk through test cases
- Communicate: Think aloud throughout the process
- β Jumping to code without planning
- β Not considering edge cases
- β Ignoring time/space complexity
- β Not testing the solution
- β Poor variable naming
- "Cracking the Coding Interview" by Gayle Laakmann McDowell
- "Elements of Programming Interviews in Python"
- "Introduction to Algorithms" by CLRS
- NeetCode
- Abdul Bari (Algorithms)
- Back To Back SWE
- Tech Dose
Contributions are welcome! Here's how you can help:
- Add alternative solutions: Different approaches to existing problems
- Improve documentation: Better explanations and comments
- Add test cases: More comprehensive testing
- Fix bugs: Report and fix any issues
- Optimize solutions: More efficient implementations
# Fork the repository
git fork https://github.com/Ak-Rajak/Most_Imp_Interview_leetcode_Questions_150.git
# Create a feature branch
git checkout -b feature/your-feature-name
# Commit your changes
git commit -m "Add: your feature description"
# Push to your branch
git push origin feature/your-feature-name
# Create a Pull RequestThis project is licensed under the MIT License - see the LICENSE file for details.
If you found this repository helpful, please consider giving it a star β!
- GitHub: Ak-Rajak
- LinkedIn: Your LinkedIn
- LeetCode: Your LeetCode Profile
- Email: your.email@example.com
- Thanks to LeetCode for providing an excellent platform for practice
- Inspired by countless developers in the community
- Special thanks to all contributors
π‘ "The only way to learn a new programming language is by writing programs in it." - Dennis Ritchie
Happy Coding! π
Made with β€οΈ and β by Ak-Rajak
β Star this repo if it helped you! β
