Skip to content

Latest commit

History

259 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

leetcode-practice-in-cpp

This repository is for my personal LeetCode practice using mainly C++.

🎯 Training Goal

My initial target is to solve one or two problems per day. If I miss any problems during the weekdays, I will catch up on them over the weekend.(to be continued...)

🚀 LeetCode Training Progress

  • 📅 Phase 1: 2025-06-09 - 2025-06-29 one problem per day
  • 📅 Phase 2: 2025-06-30 - 2025-08-24 ten problems(min) per week
  • 📅 Phase 3: 2025-08-25 - 2025-12-07 seven problems(min) per week
  • 📅 Phase 4: 2025-12-08 - now freestyle
  • ✅ Total Problems Solved: 230/230
  • 📈 Difficulty Breakdown: Easy(74) / Medium(135) / Hard(21) / Total(230)
  • 🧠 Topics Covered: Linked List, Array, Dynamic Programming, Stack, etc.

🔝 Back to Top


➡️➡️➡️📚 Table of Contents⬅️⬅️⬅️

📋 Problem Overview

📁 Folder Structure & Usage

Each problem is placed in its own folder, which contains:

  • A .hpp header file for declarations
  • A test.cpp file for testing all versions*(note: for new problems recorded from LeetCode, test.cpp may not yet exist; the original 200+ problems do have simple tests)*
  • Multiple .cpp files, each representing a different version of the solution
    • contest.cpp: The original code written during the contest or simulated contest
    • brute_force.cpp: A straightforward or initial solution outside the contest context
    • optimized.cpp: Improved or optimized solution
    • refined.cpp: A further cleaned-up or more elegant version created during later review
      • May have the same complexity as brute_force.cpp or optimized.cpp, but with better readability or slightly better runtime
  • A simple_test.hpp and simple_test.cpp pair that provide common testing utilities used by test.cpp and solution files

To compile, just compile any solution .cpp together with test.cpp and simple_test.cpp.

Example: c++ -Wall -Wextra -Werror brute_force.cpp test.cpp ../../simple_test.cpp -o test && ./test

📌 If a problem folder only contains a brute_force version, that means it's either already the best I could come up with at the time — possibly even achieving 100% runtime — or it's a reasonable enough solution for now. I’ll revisit it if I come up with a better idea or gain a deeper understanding of the problem.

🔝 Back to Top


🏆 Contest Reviews

You can find all contest summaries and review notes in the contest_review.md file.


📚 Shared Solutions

You can find all shared solution links and records in the shared.md file.


🗂️ Problem Categories

📊 Array (Total: 5 problems)

#TitleDifficultySolution FolderNotes
0485Max Consecutive OnesEasyRuntime(100%)consecutive count
0645Set MismatchEasyRuntime(100%)Find duplicate & missing → hash / counting
1365How Many Numbers Are Smaller Than The Current NumberEasyRuntime(100%)Count smaller
1470Shuffle The ArrayEasyRuntime(100%)Array reorder
1929Concatenation Of ArrayEasyRuntime(100%)Simple array manipulation

🔝 Back to Top


🌀 Backtracking (Total: 12 problems)

#TitleDifficultySolution FolderNotes
0017Letter Combinations Of A Phone NumberMediumRuntime(100%)Classic digit-to-letter mapping → DFS/backtracking
0022Generate ParenthesesMediumRuntime(100%)Backtracking with pruning → track left/right counts, reserve string capacity
0037Sudoku SolverHardRuntime(~94%)Backtracking with pruning: Brute-force uses unordered_set; Optimized uses bitmask (int row[9], col[9], block[9]) + __builtin_ctz to pick candidates efficiently
0039Combination SumMediumRuntime(sometimes 100%)Reuse numbers → sort + prune if > target, prevent duplicates via start
0040Combination Sum IIMediumRuntime(100%)Use each number once → sort + prune + skip duplicates (i > start)
0046PermutationMediumRuntime(100%)Generate all permutations, used[] + path (fast) vs swap (less memory)
0047Permutation IIMediumRuntime(~75%), classic solutionSame as 46 but with duplicatessort + skip !used[i-1] to prune
0051N QueensHardRuntime(100%)Place queens row-by-row, prune with colUsed, diag1Used, diag2Used for O(1) validity check
0077CombinationsMediumRuntime(~90%)Generate all k-combinations from 1..n → backtracking, use path and i+1 for next start
0078SubsetsMediumRuntime(100%)Generate all subsets → Backtracking (DFS) or Bit Manipulation, use path and recursion for DFS
0079Word SearchMediumRuntime(98%)DFS + backtracking on 2D grid, prune by length & char frequency, in-place visited mark
0131Palindrome PartitioningMediumRuntime(~94%) improve laterBacktracking + DP precomputation for O(1) palindrome check

🔝 Back to Top


🌲 Binary Search Tree (Total: 4 problems)

#TitleDifficultySolution FolderNotes
0098Validate Binary Search TreeMediumRuntime(100%)In-order traversal OR Recursive bounds check
0108Convert Sorted Array To Binary Search TreeEasysometimes Runtime(100%)Divide & Conquer + Recursion
0230Kth Smallest Element In A BSTMediumRuntime(100%)In-order traversal + pruning
0235Lowest Common Ancestor Of A Binary Search TreeMediumRuntime(~88%) classic solutionTop-down search using BST property

🔝 Back to Top


🔧 Bit Manipulation (Total: 14 problems)

#TitleDifficultySolution FolderNotes
0136Single NumberEasyRuntime(100%)XOR all numbers → duplicates cancel out, leaving unique
0137Single Number IIMediumRuntime(100%)Bit counting mod 3 / find unique appearing once when others appear three times
0190Reverse BitsEasyRuntime(100%)Shift & add each bit / reverse 32-bit integer
0191Number Of 1 BitsEasyRuntime(100%)Brian Kernighan’s algorithm / count set bits
0231Power Of TwoEasyRuntime(100%)n & (n - 1) == 0 trick / check single set bit
0260Single Number IIIMediumRuntime(100%)XOR all numbers → partition by rightmost differing bit → isolate two unique numbers
0268Missing NumberEasyRuntime(100%)XOR index and value → missing number remains
0318Maximum Product Of Word LengthsMediumRuntime(40-50%)Bitmask each word / compare non-overlapping masks for max length product
0338Counting BitsEasyRuntime(100%)DP + bitwise pattern / even → same as i>>1, odd → +1
0342Power Of FourEasyRuntime(100%)Check power of two + odd bit position → n & 0x55555555
0371Sum Of Two IntegersMediumRuntime(100%)XOR for sum without carry & (a & b) << 1 carry
0461Hamming DistanceEasyRuntime(100%)XOR to find differing bits + Brian Kernighan’s algorithm to count 1s
0476Number ComplementEasyRuntime(100%)Build bitmask of 1s to match bit-length → ~num & mask gives complement
0693Binary Number With Alternating BitsEasyRuntime(100%)Check alternating bit pattern using bitwise properties

🔝 Back to Top


🏗️ Design (Total: 2 problems)

#TitleDifficultySolution FolderNotes
0297Serialize And Deserialize Binary TreeHardRuntime(~30%) improve laterPreorder DFS + # null marker, istringstream token parsing
0382Linked List Random NodeMediumRuntime(100%)Reservoir Sampling for uniform random selection

🔝 Back to Top


⚡ Divide & Conquer (Total: 5 problems)

#TitleDifficultySolution FolderNotes
0050Pow(x,n)MediumRuntime(100%)Fast exponentiation, O(log n) optimization
0105Construct Binary Tree From Preorder And Inorder TraversalMediumRuntime(100%)Recursively split inorder, build subtrees
0148Sort ListMediumRuntime(60-70%)Bottom-up merge sort, O(n log n) & O(1) space
0241Different Ways To Add ParenthesesMediumRuntime(100%)Divide & Conquer with memoization
0932Beautiful ArrayMediumRuntime(100%)Divide & Conquer construction, odd/even separation

🔝 Back to Top


🎯 DP Grid / Matrix (Total: 5 problems)

#TitleDifficultySolution FolderNotes
0064Minimum Path SumMediumRuntime(100%)Grid DP → can optimize to O(n) space with rolling array(later)
0221Maximal SquareMediumRuntime(vary a lot)2D DP → dp[i][j] stores maximal square side ending at (i,j) → depends on top, left, top-left neighbors → can optimize to O(n) space
0304Range Sum Query 2D ImmutableMediumRuntime(vary a lot)2D prefix sum / summed-area table → O(1) query time
054201 MatrixMediumRuntime(~90%)2-pass DP → compute min distance to nearest 0 (top-left to bottom-right, then reverse)
3603Minimum Cost Path With Alternating Direction IIMediumRuntime(~95%) improve laterGrid DP with custom movement rule / 🏁 Biweekly 160(Q2)

🔝 Back to Top


🎯 DP Knapsack / Subset (Total: 5 problems)

#TitleDifficultySolution FolderNotes
0279Perfect SquaresMediumRuntime(~86%)Complete knapsack DP → dp[i] = min(dp[i], dp[i - j²] + 1)
0322Coin ChangeMediumRuntime(~82%)1D DP (Unbounded Knapsack) → dp[j] = min(dp[j], dp[j - coin] + 1), handle impossible states with INT_MAX-1
0416Partition Equal Subset SumMediumRuntime(~80%)0/1 Knapsack DP → `dp[j]
0474Ones And ZerosMediumRuntime(~82%)2D 0/1 Knapsack → dp[i][j] max strings with i zeros & j ones; iterate backwards to avoid reuse
0494Target SumMediumRuntime(100%)Transform to subset sum → count subsets summing to (target + sum(nums))/2, use 1D DP with backward iteration

🔝 Back to Top


🎯 DP Linear / Sequence (Total: 10 problems)

#TitleDifficultySolution FolderNotes
0053Maximum SubarrayMediumRuntime(100%)Kadane’s Algorithm → O(n) time, O(1) space
0121Best Time To Buy And Sell StockEasyRuntime(sometimes 100%)Track prefix min & update max profit in one pass
0123Best Time To Buy And Sell Stock IIIHardRuntime(sometimes 100%)Two approaches: left-right profit split (O(n) space) or 4-state DP (O(1) space)
0188Best Time To Buy And Sell Stock IVHardRuntime(~85%)State DP → buy[i], sell[i] for k transactions; optimize from 2D DP to O(k) space
0198House RobberMediumRuntime(100%)Classic DP → dp[i] = max(dp[i-1], dp[i-2] + nums[i]) → O(1) space optimized
0213House Robber IIMediumRuntime(100%)Circular variant of 0198 → run twice on [0,n-2] & [1,n-1], then max
0300Longest Increasing SubsequenceMediumRuntime(100%)Patience Sorting + Binary Search → O(n log n)
0309Best Time To Buy And Sell Stock With CooldownMediumRuntime(100%)State-machine DP → hold / cool / rest states; enforces 1-day cooldown
0413Arithmetic SlicesMediumRuntime(100%)DP → dp[i] = dp[i-1] + 1 if valid, sum(dp) for answer
0714Best Time To Buy And Sell Stock With Transaction FeeMediumRuntime(100%)DP with two states → hold (keep) & empty; update daily max profit; subtract fee on sell

🔝 Back to Top


🎯 DP Math (Total: 6 problems)

#TitleDifficultySolution FolderNotes
0070Climbing StairsEasyRuntime(100%)Fibonacci variant with safe integer handling
0091Decode WaysMediumRuntime(100%)DP → dp[i] = ways to decode s[0..i-1]; careful handling of 0 and two-digit numbers (10..26)
0118Pascals TriangleEasyRuntime(100%)Generate triangle row by row → row[j] = prev_row[j-1] + prev_row[j], edge 1’s
0264Ugly Number IIMediumRuntime(100%)DP + 3 pointers → generate sequence by merging ×2,×3,×5
0313Super Ugly NumberMediumRuntime(~89%)DP + k pointers → merge k prime-generated streams, avoid duplicates
0509Fibonacci NumberEasyRuntime(sometimes 100%)Classic DP → optimized to rolling variables

🔝 Back to Top


🎯 DP String / Edit (Total: 5 problems)

#TitleDifficultySolution FolderNotes
0010Regular Expression MatchingHardRuntime(~52%) classic solution2D DP → simulate regex with . and *, careful initialization and transitions
0072Edit DistanceMediumRuntime(>70%)2D DP → dp[i][j] = min ops to convert prefix of word1→word2; handles insert/delete/replace
0139Word BreakMediumRuntime(100%)DP → dp[i] = whether s[0..i-1] can be segmented; check all words ending at i
0583Delete Operation For Two StringsMediumRuntime(65~90%)2D DP → LCS length → min deletions = len1 + len2 - 2*LCS; can optimize to O(n) space with rolling array
1143Longest Common SubsequenceMediumRuntime(vary a lot) classic solutionClassic LCS → 2D DP; dp[i][j] = LCS of prefixes; can optimize to O(min(m,n)) space

🔝 Back to Top


🌐 Flood Fill / Connected Components (Total: 6 problems)

#TitleDifficultySolution FolderNotes
0130Surrounded RegionsMediumRuntime(100%)DFS with temporary marking + revert step
0417Pacific Atlantic Water FlowMediumRuntime(sometimes 100%)Reverse flood fill from oceans / DFS
0547Number Of ProvincesMediumRuntime(100%)Connected components in adjacency matrix / DFS
0695Max Area Of IslandMediumRuntime(100%)Classic flood fill / DFS variants
0934Shortest BridgeMediumRuntime(vary a lot)Hybrid DFS + BFS: mark one island, expand to find shortest bridge
3619Count Islands With Total Value Divisible By KMediumRuntime(~90%) classic solutionFlood fill via DFS and BFS comparison / 🏁 Biweekly 161(Q2)

🔝 Back to Top


🕸️ Graph & Topological Sort (Total: 4 problems)

#TitleDifficultySolution FolderNotes
0207Course ScheduleMediumRuntime(79%-100%)Cycle detection, DAG check
0310Minimum Height TreesMediumRuntime(~60%)Trim leaves iteratively, tree centers
0332Reconstruct ItineraryHardRuntime(vary a lot)Eulerian path, DFS + backtracking, lexical order
3620Network Recovery PathwaysHardRuntime(>90%)DAG shortest path + topo sort + binary search / / 🏁 Biweekly 161(Q3)

🔝 Back to Top


🧭 Greedy (Total: 19 problems)

#TitleDifficultySolution FolderNotes
0011Container With Most WaterMediumRuntime(sometimes 100%)Two pointers with greedy: always move the shorter line
0122Best Time To Buy And Sell Stock IIMediumRuntime(100%)Greedy → accumulate all positive price differences
0135CandyHardRuntime(100%)Greedy + two-pass scan: take max(left[i], right[i])
0169Majority ElementEasyRuntime(100%)Boyer-Moore Voting: greedy cancellation of minority elements
0179Largest NumberMediumRuntime(~77%), classic solutionGreedy + custom sorting: sort by a + b > b + a
0376Wiggle SubsequenceMediumRuntime(100%)Greedy → track up / down to count alternating differences
0406Queue Reconstruction By HeightMediumRuntime(~71%) improve laterGreedy + sort by descending height, insert each person at index k; segment tree can optimize to O(n log n)
0435Non_Overlapping_IntervalsMediumRuntime(~73%) classic solutionGreedy + sorting by end time: always keep the interval that ends earliest
0452Minimum Number Of Arrows To Burst BallonsMediumRuntime(~32%) classic solutionGreedy + sorting by end time: shoot arrows at earliest possible end
0455Assign CookiesEasyRuntime(sometimes 100%)Greedy + two pointers after sorting: assign smallest possible cookie to each child
0605Can Place FlowersEasyRuntime(100%)Greedy: check left/right neighbors, plant if both empty, early stop if n == 0
0646Maximum Length Of Pair ChainMediumRuntime(80-90%)Greedy: sort by pair end, always pick next pair with start > previous end
0665Non Decreasing ArrayMediumRuntime(100%)Greedy: allow at most one violation, fix locally by lowering nums[i] or raising nums[i+1]
0763Partition LabelsMediumRuntime(100%)Greedy + last occurrence: expand partition until reaching farthest boundary
0768Max Chunks To Make Sorted IIHardRuntime(100%)Greedy + monotonic stack: track max of each chunk, merge when arr[i] < stack.top()
0769Max Chunks To Make SortedMediumRuntime(100%)Greedy + prefix max: when cur_max == i, one chunk can be cut
0870Advantage ShuffleMediumRuntime(~99%)use largest to beat largest, otherwise sacrifice smallest
3635Earlies Finish Time For Land And Water Rides IIMediumRuntime(~83%), classic solutionGreedy on earliest finish time in both orders (land→water / water→land) / 🏁 Biweekly 162(Q3)
3664Two-Letter Card GameMediumRuntime varies, classic solutionCount cards by categories and use greedy pairing with leftovers (both, left, right) / 🏁 Biweekly 164(Q2)

🔝 Back to Top


🧩 Hash Map (Total: 11 problems)

#TitleDifficultySolution FolderNotes
0001Two SumEasyRuntime(100%)One-pass hash map / complement lookup
0128Longest Consecutive SequenceMediumRuntime(vary a lot)Hash set / sequence start detection / O(n)
0149Max Points On A LineHardRuntime(~92%)Slope hash map / duplicates / vertical lines
0202Happy NumberEasyRuntime(100%)Hash set / cycle detection
0205Isomorphic StringsEasyRuntime(100%)Two-way mapping / fixed array optimization
0217Contains DuplicateEasyRuntime(~70%)Hash set / O(n) scan
0242Valid AnagramEasyRuntime(100%)Frequency counting / O(1) space
0387First Unique Character In A StringEasyRuntime(~70%, can improve later)Array or hash map / two-pass scan
0409Longest PalindromeEasyRuntime(100%)Frequency counting / even part + odd center
0594Longest Harmonious SubsequenceEasyRuntime(>80%)Frequency hash map / check consecutive numbers
0697Degree Of An ArrayEasyRuntime(vary a lot)Count / first & last index / shortest subarray

🔝 Back to Top


🏔️ Heap / QuickSelect / Bucket (Total: 5 problems)

#TitleDifficultySolution FolderNotes
0023Merge K Sorted ListsHardRuntime(sometimes 100%)min-heap (priority queue)
0215Kth Largest Element In An ArrayMediumRuntime(>90%)heap vs quick select
0218The Skyline ProblemHardRuntime(~100%)sweep line + max-heap (priority queue)
0347Top K Frequent ElementsMediumRuntime(100%)bucket sort vs quick select
0451Sort Characters By FrequencyMediumRuntime(sometimes 100%)bucket sort

🔝 Back to Top


🔗 Linked List (Total: 9 problems)

#TitleDifficultySolution FolderNotes
0021Merge Two Sorted ListsEasyRuntime(100%)Recursive vs Iterative
0024Swap Nodes In PairsMediumRuntime(100%)Pairwise swapping / Dummy node
0083Remove Duplicates From Sorted ListEasyRuntime(100%)Skip consecutive equals
0086Partition ListMediumRuntime(100%)Dummy node / In-place insertion
0138Copy List With Random PointerMediumRuntime(>90%,sometimes 100%)Hash Map / In-place / O(1) extra space optimized
0206Reverse Linked ListEasyRuntime(100%)Tail-cutting / Recursive / Iterative
0234Palindrome Linked ListEasyRuntime(100%)Slow/Fast pointers / Reverse second half / In-place comparison
0237Delete Node In A Linked ListMediumRuntime(Not 100%), good enoughLoop-copy / O(1) overwrite
0328Odd Even Linked ListMediumRuntime(100%)Odd/Even chain splitting / O(1) space

🔝 Back to Top


📐 Math (Total: 15 problems)

#TitleDifficultySolution FolderNotes
0089Gray CodeMediumRuntime(100%)Generate Gray codes using i ^ (i >> 1) formula
0168Excel Sheet Column TitleEasyRuntime(100%)Base-26 conversion with A–Z, subtract 1 each step to handle 1-based system
0172Factorial Trailing ZeroesMediumRuntime(100%)Count factors of 5 in n!; trailing zeros = sum of n/5 + n/25 + n/125 + ...
0204Count PrimesMediumRuntime(~90%)Use Sieve of Eratosthenes; mark multiples; accumulate counts primes
0233Number Of Digit OneHardRuntime(100%)Digit counting by high/cur/low parts per digit
0326Power Of ThreeEasyRuntime(sometimes 100%)Check if n is divisible by 3 repeatedly; return true if final n is 1
0343Integer BreakMediumRuntime(100%)Break n into as many 3s as possible; handle mod=1 by turning 3+12+2
0400Nth DigitMediumRuntime(100%)Digit block skipping → locate number & digit
0462Minimum Moves To Equal Array Elements IIMediumRuntime(sometimes 100%)Minimize total distance by moving all elements to the median
0470Implement Rand10() Using Rand7()MediumRuntime(vary a lot)Use rejection sampling: generate 1–49 via (rand7()-1)*7+rand7(), keep ≤40 and map to 1–10
0504Base 7EasyRuntime(100%)Convert integer to base 7; handle sign; build digits in reverse
06502 Keys KeyboardMediumRuntime(100%)Min steps = sum of prime factors of n
1823Find The Winner Of The Circular GameMediumRuntime(100%)Josephus problem — recurrence: dp = (dp + k) % i
3618Split Array By Prime IndicesMediumRuntime(>70%) classic solutionNumber theory + sieve of Eratosthenes / 🏁 Biweekly 161(Q1)
3648Minimum Sensors To Cover GridMediumRuntime(100%)Coverage square side = 2k+1; ceil-div in both dims / 🏁 Biweekly 163(Q1)

🔝 Back to Top


📐 Math (Total: 3 problems)

#TitleDifficultySolution FolderNotes
0503Next Greater Element IIMediumRuntime(sometimes 100%)Monotonic stack / Circular array / Push indices only in first pass
0739Daily TemperaturesMediumRuntime(~100%)Monotonic stack / Next greater element
1475Final Prices With a Special Discount in a ShopEasyRuntime(100%)Maintain a monotonic increasing stack; find the next element <= current to compute discount

🔝 Back to Top


➕ Prefix Sum (Total: 6 problems)

#TitleDifficultySolution FolderNotes
0238Product Of Array Except SelfMediumRuntime(100%)Prefix product (left) × suffix product (right) without division
0303Range Sum Query ImmutableEasyRuntime(100%)Prefix sum with O(1) range query
0528Random Pick With WeightMediumRuntime(vary a lot)Prefix sum + binary search for weighted random selection
0560Subarray Sum Equals KMediumRuntime(~50%)Prefix sum + hash map to count matching prefix differences
0724Find Pivot IndexEasyRuntime(100%)Compare left and right prefix sum
1480Running Sum Of 1d ArrayEasyRuntime(100%)Basic prefix sum building cumulatively

🔝 Back to Top


🔍 Search (Total: 14 problems)

#TitleDifficultySolution FolderNotes
0004Median Of Two Sorted ArraysHardRuntime(100%)Binary search on partition of shorter array → O(log(min(m,n)))
0033Search In Rotated Sorted ArrayMediumRuntime(100%)Binary search with rotation awareness → O(log n)
0034Find First And Last Position Of Element In Sorted ArrayMediumRuntime(100%)Two binary searches to find left and right boundaries → O(log n)
0035Search Insert PositionEasyRuntime(100%)Lower Bound implementation → O(log n)
0069Sqrt(x)EasyRuntime(100%)Binary search for integer square root → O(log n)
0074Search A 2D MatrixMediumRuntime(100%)Treat matrix as 1D array + binary search → O(log(m·n))
0081Search In Rotated Sorted Array IIMediumRuntime(100%)Binary search with rotation + duplicates → O(n) worst case
0153Find Minimum In Rotated Sorted ArrayMediumRuntime(100%)Binary search for rotation pivot → O(log n)
0154Find Minimum In Rotated Sorted Array IIHardRuntime(100%)Binary Search with Duplicates
0240Search A 2D Matrix IIMediumRuntime(vary a lot), classic solutionMonotonic matrix search from top-right corner → O(m+n)
0278First Bad VersionEasyRuntime(~55%) classic solutionFind first true with minimal API calls / Lower Bound
0540Single Element In A Sorted ArrayMediumRuntime(100%)Binary search with pair index check → O(log n)
0647Palindromic SubstringsMediumRuntime(~70%)Expand-around-center on all 2n−1 centers → O(n²)
0704Binary SearchEasyRuntime(100%)Classic binary search on sorted array

🔝 Back to Top


🛣️ Shortest Path (Total: 2 problems)

#TitleDifficultySolution FolderNotes
0126Word Ladder IIHardRuntime(~45%)BFS to find shortest depth + backtracking to reconstruct all shortest paths
3650Minimum Cost Path With Edge ReversalsMediumRuntime(~95%)Model each edge as two directed edges (original cost and 2× cost for reversal) and solve with Dijkstra / 🏁 Biweekly 163(Q3)

🔝 Back to Top


🧮 Simulation (Total: 10 problems)

#TitleDifficultySolution FolderNotes
0048Rotate ImageMediumRuntime(100%)Simulate 90° rotation by transpose + row reversal
0054Spiral MatrixMediumRuntime(100%)Simulate matrix traversal by shrinking boundaries
0059Spiral Matrix IIMediumRuntime(100%)Simulate spiral filling using 4 dynamic boundaries
0384Shuffle An ArrayMediumRuntime(vary a lot)Fisher-Yates shuffle to generate uniform random permutation; store original array for reset
0415Add StringsEasyRuntime(100%)Simulate digit-by-digit addition / carry tracking
0448Find All Numbers Disappeared In An ArrayEasyRuntime(vary a lot), classic solutionMark visited indices in-place using negation
0566Reshape The MatrixEasyRuntime(100%)Flatten and remap elements in row-major order; check reshape validity
0796Rotate StringEasyRuntime(100%)Simulate string rotation by manual character comparison
3602Hexadecimal And Hexatrigesimal ConversionEasyRuntime(100%)Simulate base conversion with custom digit set / 🏁 Biweekly 160(Q1)
3633Earlies Finish Time For Land And Water Rides IEasyRuntime(20%), better solution in 3635Brute-force simulate both orders (land→water / water→land) / 🏁 Biweekly 162(Q1)
3663Find The Least Frequent DigitEasyRuntime(100%)Counting digits / 🏁 Biweekly 164(Q1)

🔝 Back to Top


🌊 Sliding Window (Total: 3 problems)

#TitleDifficultySolution FolderNotes
0076Minimum Window SubstringHardRuntime(100%)Classic sliding window with char count & shrink
0239Sliding Window MaximumHardRuntime(~99%)Monotonic deque & heap approaches
3634Minimum Removals To Balance ArrayMediumRuntime(vary a lot), classic solutionSort + sliding window (two pointers) / 🏁 Biweekly 162(Q2)

🔝 Back to Top


🧱 Stack & Queue (Total: 11 problems)

#TitleDifficultySolution FolderNotes
0020Valid ParenthesesEasyRuntime(100%)Stack / Bracket matching
0150Evaluate Reverse Polish NotationMediumRuntime(100%)Stack / Evaluate postfix expression
0155Min StackMediumRuntime(~45% but classic, can improve later)Two-stack approach / O(1) min
0225Implement Stack Using QueuesEasyRuntime(100%)Single queue rotation / Push O(n), others O(1)
0227Basic Calculator IIMediumRuntime(sometimes 100%)Operator precedence / O(n) scan
0232Implement Queue Using StacksEasyRuntime(100%)Two-stack queue / Amortized O(1) ops
0295Find Median From Data StreamHardRuntime(varies a lot)Two heaps / O(log n) insert, O(1) median
0394Decode StringMediumRuntime(100%)Recursion & Stack / Nested string decode
0636Exclusive Time Of FunctionsMediumRuntime(100%)Stack / Function call simulation
0946Validate Stack SequencesMediumRuntime(100%)Simulate push/pop behavior with a real stack
1441Build An Array With Stack OperationsMediumRuntime(100%)Stack simulation / Sequential push-pop control

🔝 Back to Top


🔤 String Processing (Total: 5 problems)

#TitleDifficultySolution FolderNotes
0006Zigzag ConversionMediumRuntime(100%)Simulation + direction control + reserve optimization
0008String To Interger AtoiMediumRuntime(100%)Manual parse + overflow clamp + long long use
0028Find The Index Of The First Occurrence In A StringEasyRuntime(100%)KMP algorithm + LPS array + O(m+n)
0067Add BinaryEasyRuntime(100%)Reverse + carry handling + reserve optimization
0151Reverse Words In A StringMediumRuntime(100%)Backward scan + substr + reserve optimization

🔝 Back to Top


💡 Tree DP / Path Sum (Total: 4 problems)

#TitleDifficultySolution FolderNotes
0113Path Sum IIMediumRuntime(100%)DFS + Backtracking
0124Binary Tree Maximum Path SumHardRuntime(100%)DFS + Tree DP
0437Path Sum IIIMediumRuntime(100%)DFS + Prefix Sum + HashMap
0543Diameter Of Binary TreeEasyRuntime(100%)DFS + Tree DP

🔝 Back to Top


🌳 Tree Traversal (Total: 12 problems)

#TitleDifficultySolution FolderNotes
0094Binary Tree Inorder TraversalEasyRuntime(100%)DFS recursion
0101Symmetric TreeEasyRuntime(100%)DFS recursion & BFS queue mirror check
0102Binary Tree Level Order TraversalMediumRuntime(100%)BFS using queue
0103Binary Tree Zigzag Level Order TraversalMediumRuntime(100%)BFS with alternating direction
0104Maximum Depth Of Binary TreeEasyRuntime(100%)DFS recursion & BFS level count
0110Balanced Binary TreeEasyRuntime(100%)DFS + pruning, early exit on unbalanced
0144Binary Tree Preorder TraversalEasyRuntime(100%)Iterative DFS using stack, Root→Left→Right
0226Invert Binary TreeEasyRuntime(100%)DFS recursion & BFS swap children
0236Lowest Common Ancestor Of A Binary TreeMediumRuntime(~60%) classic solutionPost-order recursion (LCA logic)
0257Binary Tree PathsEasyRuntime(100%)DFS recursion, build path strings root→leaf
0637Average Of Levels In Binary TreeEasyRuntime(100%)BFS level-order sum & count
1110Delete Nodes And Return ForestMediumRuntime(vary a lot)DFS + post-order, handle forest of trees

🔝 Back to Top


🪝 Two Pointers (Total: 17 problems)

#TitleDifficultySolution FolderNotes
0003Longest Substring Without Repeating CharactersMediumRuntime(100%)Sliding window (brute-force, map, array) / O(n) optimized
0005Longest Palindromic SubstringMediumRuntime(~90%)Expand Around Center / Two pointers / O(n²)
00153SumMediumRuntime(~53%), classic solutionSort + two pointers / Skip duplicates / O(n²)
0019Remove Nth Node From End Of ListMediumRuntime(100%)Two pointers with dummy head / Fixed gap (n+1) / One pass
0075Sort ColorsMediumRuntime(100%)Dutch National Flag / Three pointers / In-place / O(n)
0088Merge Sorted ArrayEasyRuntime(100%)Two pointers from back / In-place merge / O(m+n)
0142Linked List Cycle IIMediumRuntime(80-90%)Fast-slow pointer to find cycle start
0160Intersection Of Two Linked ListsEasyRuntime(~80%), classic solutionTwo-pointer with list switching
0167Two Sum II Input Array Is SortedMediumRuntime(100%)Two-pointer / Sorted array
0287Find The Duplicate NumberMediumRuntime(~70%) classic solutionFloyd’s cycle (fast/slow) & Binary search
0392Is SubsequenceEasyRuntime(100%)Two-pointer / String scan
0524Longest Word In Dictionary Through DeletingMediumRuntime(100%)Two-pointer subsequence check / Track longest + lexicographically smallest
0633Sum Of Square NumbersMediumRuntime(100%)Two pointers (0 ~ √c) / Check sum of squares
0680Valid Palindrome IIEasyRuntime(sometimes 100%)Two-pointer with one deletion / Check substrings when mismatch
0696Count Binary SubstringsEasyRuntime(100%)Track consecutive 0/1 groups / Single pass O(n) / Constant space
0876Middle Of The Linked ListEasyRuntime(100%)Fast-slow pointer on Linked List
3649Number Of Perfect PairsMediumRuntime(vary a lot)Sort + two pointers on absolute values / Count pairs satisfying y ≤ 2x / 🏁 Biweekly 163(Q2)

🔝 Back to Top


About

This repository is for my personal LeetCode practice using mainly C++.

Resources

Stars

2 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages