342 posts found

[Hard] 2539. Count the Number of Good Subsequences

Given a string s, return the number of non-empty good subsequences of s. A subsequence is good if every character in it appears the same number of times. Answer modulo...
leetcodehardcombinatorics

[Medium] 221. Maximal Square

Given an m x n binary matrix filled with '0's and '1's, find the largest square containing only '1's and return its area.
leetcodemediumdynamic-programming

[Medium] 274. H-Index

Given an array of integers citations where citations[i] is the number of citations a researcher received for their i-th paper, return the researcher’s h-index.
leetcodemediumsorting

[Medium] 92. Reverse Linked List II

Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right...
leetcodemediumlinked-list

[Medium] 1669. Merge In Between Linked Lists

You are given two linked lists: list1 and list2 of sizes n and m respectively. Remove list1’s nodes from the a-th node to the b-th node (0-indexed), and put list2...
leetcodemediumlinked-list

[Medium] 894. All Possible Full Binary Trees

Given an integer n, return a list of all possible full binary trees with n nodes. Each node has value 0. A full binary tree is a tree where every...
leetcodemediumtreerecursionmemoization

[Medium] 2365. Task Scheduler II

You are given a list of tasks to complete in order. Each day you can complete one task. After completing a task of type t, you must wait at least...
leetcodemediumhash-mapsimulation

[Medium] 382. Linked List Random Node

Given a singly linked list, return a random node’s value. Each node must have an equal probability of being chosen.
leetcodemediumlinked-listrandomized

[Medium] 1328. Break a Palindrome

Given a palindromic string palindrome, replace exactly one character to make it not a palindrome, and make the resulting string the lexicographically smallest possible. Return the result, or an empty...
leetcodemediumstringgreedy

[Medium] 2270. Number of Ways to Split Array

You are given a 0-indexed integer array nums of length n. A split at index i is valid if the sum of the first i + 1 elements is greater...
leetcodemediumprefix-sumarray

[Medium] 73. Set Matrix Zeroes

Given an m x n integer matrix, if an element is 0, set its entire row and column to 0. You must do it in place.
leetcodemediummatrixarray

[Medium] 261. Graph Valid Tree

Given n nodes labeled 0 to n-1 and a list of undirected edges, determine if these edges form a valid tree.
leetcodemediumgraphdsudfs

[Medium] 260. Single Number III

Given an integer array nums where exactly two elements appear once and all other elements appear exactly twice, find the two elements that appear only once. Return them in any...
leetcodemediumbit-manipulation

[Medium] 1870. Minimum Speed to Arrive on Time

You are given n train rides with distances dist[i]. Each train departs at an integer hour, so you must wait until the next whole hour to board the next train...
leetcodemediumbinary-search

[Medium] 1188. Design Bounded Blocking Queue

Implement a thread-safe bounded blocking queue with the following methods: BoundedBlockingQueue(int capacity) – initialize with max capacity void enqueue(int element) – add element to the back; blocks if the queue...
leetcodemediumconcurrencydesign

[Medium] 1115. Print FooBar Alternately

Two different threads will call foo and bar respectively. Design a mechanism so that "foobar" is printed n times by alternating between the two threads: foo always prints first, then...
leetcodemediumconcurrency

[Medium] 151. Reverse Words in a String

Given an input string s, reverse the order of the words. A word is a sequence of non-space characters. Words are separated by at least one space. Return a string...
leetcodemediumstringtwo-pointers

[Easy] 389. Find the Difference

You are given two strings s and t. String t is generated by randomly shuffling s and then adding one more letter at a random position. Return the letter that...
leetcodeeasybit-manipulationstring

[Easy] 1768. Merge Strings Alternately

Given two strings word1 and word2, merge them by adding letters in alternating order, starting with word1. If one string is longer, append the remaining letters at the end.
leetcodeeasystringtwo-pointers

[Medium] 1087. Brace Expansion

Given a string s representing a list of words, where each letter can be replaced by a group of letters inside braces {a,b,c}, return all possible words in sorted order....
leetcodemediumbacktrackingstring

[Medium] 918. Maximum Sum Circular Subarray

Given a circular integer array nums, find the maximum possible sum of a non-empty subarray. A circular subarray can wrap around the end back to the beginning.
leetcodemediumdparraykadane

[Medium] 341. Flatten Nested List Iterator

You are given a nested list of integers nestedList. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator...
leetcodemediumdesignstackiterator

[Medium] 134. Gas Station

There are n gas stations along a circular route. Station i has gas[i] units of gas. It costs cost[i] units to travel from station i to station i+1. Starting with...
leetcodemediumgreedyarray

[Medium] 713. Subarray Product Less Than K

Given an array of positive integers nums and an integer k, return the number of contiguous subarrays where the product of all elements is strictly less than k.
leetcodemediumsliding-windowtwo-pointers

[Medium] 1197. Minimum Knight Moves

In an infinite chess board with coordinates from -infinity to +infinity, a knight starts at (0, 0). Return the minimum number of moves to reach (x, y).
leetcodemediumbfs

[Medium] 1146. Snapshot Array

Implement a SnapshotArray that supports: SnapshotArray(int length) – initializes an array of the given length (all zeros) void set(index, val) – sets the element at index to val int snap()...
leetcodemediumdesignbinary-search

[Medium] 362. Design Hit Counter

Design a hit counter that counts the number of hits received in the past 5 minutes (300 seconds).
leetcodemediumdesignqueue

[Medium] 1448. Count Good Nodes in Binary Tree

Given a binary tree, a node X is good if there is no node with a value greater than X on the path from root to X. Return the number...
leetcodemediumtreedfsbfs

[Medium] 1376. Time Needed to Inform All Employees

A company has n employees numbered 0 to n-1. Each employee has exactly one direct manager given in manager[i], except the head of the company (manager[headID] == -1). An employee...
leetcodemediumtreedfsbfs

[Medium] 2406. Divide Intervals Into Minimum Number of Groups

You are given a 2D array intervals where intervals[i] = [left_i, right_i] represents the inclusive interval [left_i, right_i]. Divide the intervals into one or more groups such that no two...
leetcodemediumgreedyheapintervals

[Medium] 433. Minimum Genetic Mutation

A gene string is represented by an 8-character string of 'A', 'C', 'G', and 'T'. Given startGene, endGene, and a bank of valid gene strings, return the minimum number of...
leetcodemediumbfsstring

[Medium] 841. Keys and Rooms

There are n rooms labeled 0 to n-1. All rooms are locked except room 0. Each room contains a set of keys to other rooms. Given rooms[i] – the set...
leetcodemediumgraphdfsbfs

[Medium] 1091. Shortest Path in Binary Matrix

Given an n x n binary matrix grid, return the length of the shortest clear path from top-left (0,0) to bottom-right (n-1,n-1). A clear path consists of cells with value...
leetcodemediumgraphbfs

[Easy] 876. Middle of the Linked List

Given the head of a singly linked list, return the middle node. If there are two middle nodes, return the second middle node.
leetcodeeasylinked-listtwo-pointers

[Medium] 1202. Smallest String With Swaps

You are given a string s and an array of index pairs pairs where pairs[i] = [a, b] indicates you can swap the characters at indices a and b any...
leetcodemediumstringgraphdsu

[Medium] 1584. Min Cost to Connect All Points

You are given an array points where points[i] = [xi, yi] represents a point on the 2D plane. The cost to connect two points is the Manhattan distance: |xi -...
leetcodemediumgraphmstdsu

[Medium] 249. Group Shifted Strings

We can “shift” a string by shifting each character to its successive character (with z wrapping to a). For example, "abc" can be shifted to "bcd", …, "xyz", "yza", "zab"....
leetcodemediumstringhash

[Easy] 383. Ransom Note

Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine. Each letter in magazine can only be used once.
leetcodeeasystringhash

[Easy] 242. Valid Anagram

Given two strings s and t, return true if t is an anagram of s, and false otherwise. An anagram uses the exact same characters with the exact same frequencies....
leetcodeeasystringhash

[Easy] 219. Contains Duplicate II

Given an integer array nums and an integer k, return true if there are two distinct indices i and j such that nums[i] == nums[j] and abs(i - j) <=...
leetcodeeasyarrayhashsliding-window

[Easy] 217. Contains Duplicate

Given an integer array nums, return true if any value appears at least twice, and false if every element is distinct.
leetcodeeasyarrayhash

[Medium] 113. Path Sum II

Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values equals targetSum. Each path should be returned as...
leetcodemediumtreedfsbacktracking

[Easy] 94. Binary Tree Inorder Traversal

Given the root of a binary tree, return the inorder traversal of its nodes’ values. Inorder visits: left → root → right.
leetcodeeasytreedfs

[Easy] 543. Diameter of Binary Tree

Given the root of a binary tree, return the length of the diameter of the tree. The diameter is the length of the longest path between any two nodes (measured...
leetcodeeasytreedfs

[Easy] 145. Binary Tree Postorder Traversal

Given the root of a binary tree, return the postorder traversal of its nodes’ values. Postorder visits: left → right → root.
leetcodeeasytreedfs

[Easy] 144. Binary Tree Preorder Traversal

Given the root of a binary tree, return the preorder traversal of its nodes’ values. Preorder visits: root → left → right.
leetcodeeasytreedfs

[Easy] 112. Path Sum

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path...
leetcodeeasytreedfs

[Easy] 110. Balanced Binary Tree

Given a binary tree, determine if it is height-balanced. A height-balanced binary tree is one in which the depth of the two subtrees of every node never differs by more...
leetcodeeasytreedfs

[Medium] 78. Subsets

Given an integer array nums of unique elements, return all possible subsets (the power set). The solution must not contain duplicate subsets.
leetcodemediumbacktracking

[Medium] 523. Continuous Subarray Sum

Given an integer array nums and an integer k, return true if nums has a good subarray, i.e., a contiguous subarray of length at least 2 whose sum is a...
leetcodemediumprefix-sumhash

[Medium] 348. Design Tic-Tac-Toe

Design a Tic-Tac-Toe game that is played on an n x n board between two players. A move is guaranteed to be valid and is placed on an empty block....
leetcodemediumdesignmatrix

[Easy] 1275. Find Winner on a Tic Tac Toe Game

Tic-tac-toe is played on a 3 x 3 grid by two players A and B. Player A always plays first. Given an array moves where moves[i] = [row, col] indicates...
leetcodeeasysimulationmatrix

[Medium] 59. Spiral Matrix II

Given a positive integer n, generate an n × n matrix filled with elements from 1 to n² in spiral order (clockwise).
leetcodemediummatrixsimulation

[Medium] 43. Multiply Strings

Given two non-negative integers represented as strings num1 and num2, return their product as a string. You cannot convert the inputs to integers directly (numbers can be very large).
leetcodemediumstringmathsimulation

[Hard] 42. Trapping Rain Water

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
leetcodehardtwo-pointersstackdp

[Medium] 38. Count and Say

The count-and-say sequence is a sequence of digit strings defined by the recursive formula:
leetcodemediumstringsimulation

[Hard] 23. Merge k Sorted Lists

You are given an array of k linked lists, each sorted in ascending order. Merge all the linked lists into one sorted linked list and return it.
leetcodehardlinked-listdivide-and-conquerheap

[Easy] 893. Groups of Special-Equivalent Strings

Two strings are special-equivalent if you can swap characters at even indices among themselves and swap characters at odd indices among themselves, any number of times. Return the number of...
leetcodeeasystringhash

[Medium] 36. Valid Sudoku

Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
leetcodemediummathbit-manipulation

[Medium] 29. Divide Two Integers

Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator. Return the quotient after dividing dividend by divisor. The integer division should truncate toward...
leetcodemediummathbit-manipulation

[Medium] 416. Partition Equal Subset Sum

Given an integer array nums, return true if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or false...
leetcodemediumdynamic-programming

[Medium] 155. Min Stack

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
leetcodemediumstack

[Medium] 91. Decode Ways

A message containing letters from A-Z can be encoded into numbers using the following mapping:
leetcodemediumdynamic-programming

[Hard] 1944. Number of Visible People in a Queue

There are n people standing in a queue numbered from 0 to n - 1 from left to right. You are given an array heights of distinct integers where heights[i]...
leetcodehardstackmonotonic-stack

[Medium] 3112. Minimum Time to Visit Disappearing Nodes

There exists an undirected tree with n nodes numbered 0 to n-1. You are given a 2D integer array edges of length n-1, where edges[i] = [ui, vi, lengthi] indicates...
leetcodemediumgraphshortest-pathdijkstra

[Medium] 210. Course Schedule II

You have numCourses courses labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] means you must take course bi before course...
leetcodemediumgraphtopological-sort

[Medium] 1488. Avoid Flood in The City

You have infinitely many lakes, all initially empty. When it rains on lake n, that lake becomes full. If it rains on a lake that is already full, a flood...
leetcodemediumarraygreedybinary-searchset

[Medium] 875. Koko Eating Bananas

Koko has n piles of bananas; the i-th pile has piles[i] bananas. The guards return in h hours. Koko can choose an integer eating speed k (bananas per hour). Each...
leetcodemediumarraybinary-search

[Medium] 532. K-diff Pairs in an Array

Given an array of integers nums and an integer k, return the number of unique k-diff pairs in the array.
leetcodemediumarrayhash-table

[Medium] 3439. Reschedule Meetings for Maximum Free Time I

You are given an integer eventTime (the event runs from time 0 to eventTime) and two arrays startTime and endTime representing n non-overlapping meetings. You may reschedule at most k...
leetcodemediumarrayintervalssliding-windowprefix-sum

[Easy] 252. Meeting Rooms

Given an array of meeting time intervals where intervals[i] = [starti, endi], determine if a person could attend all meetings.
leetcodeeasyarraysortingintervals

[Medium] 1109. Corporate Flight Bookings

There are n flights labeled from 1 to n. You are given an array of flight bookings where bookings[i] = [firsti, lasti, seatsi] represents a booking for flights firsti through...
leetcodemediumarrayprefix-sumdifference-array

[Medium] 787. Cheapest Flights Within K Stops

There are n cities connected by some number of flights. You are given an array flights where flights[i] = [fromi, toi, pricei] indicates that there is a flight from city...
leetcodemediumgraphshortest-pathdynamic-programmingbellman-ford

[Medium] 743. Network Delay Time

You are given a network of n nodes, labeled from 1 to n. You are also given times, a list of travel times as directed edges times[i] = (ui, vi,...
leetcodemediumgraphshortest-pathdijkstra

[Medium] 974. Subarray Sums Divisible by K

Given an integer array nums and an integer k, return the number of non-empty subarrays that have a sum divisible by k.
leetcodemediumarrayhash-tableprefix-sum

[Hard] 843. Guess the Word

This is an interactive problem.
leetcodehardarraystringinteractiveminmax

[Medium] 560. Subarray Sum Equals K

Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k.
leetcodemediumarrayhash-tableprefix-sum

[Medium] 325. Maximum Size Subarray Sum Equals k

Given an integer array nums and an integer k, return the maximum length of a subarray that sums to k. If there is no such subarray, return 0.
leetcodemediumarrayhash-tableprefix-sum

[Hard] 44. Wildcard Matching

Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*' where:
leetcodehardstringdynamic-programminggreedytwo-pointers

[Medium] 981. Time Based Key-Value Store

Design a time-based key-value data structure that can store multiple values for the same key at different timestamps and retrieve the key’s value at a certain timestamp.
leetcodemediumhash-tablebinary-searchdesign

[Medium] 162. Find Peak Element

A peak element is an element that is strictly greater than its neighbors.
leetcodemediumarraybinary-search

[Easy] 35. Search Insert Position

Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it...
leetcodeeasyarraybinary-search

[Medium] 739. Daily Temperatures

Given an array of integers temperatures representing the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the i-th day...
leetcodemediumarraystackmonotonic-stack

[Medium] 2080. Range Frequency Queries

Design a data structure that can query the frequency of a given value in a given subarray.
leetcodemediumarrayhash-mapbinary-searchdesign

[Medium] 238. Product of Array Except Self

Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].
leetcodemediumarrayprefix-sumtwo-pointers

[Hard] 1136. Parallel Courses

You are given an integer n, which indicates that there are n courses labeled from 1 to n. You are also given an array relations where relations[i] = [prevCoursei, nextCoursei],...
leetcodehardgraphtopological-sortdfsdynamic-programming

[Medium] 209. Minimum Size Subarray Sum

Given an array of positive integers nums and a positive integer target, return the minimal length of a subarray whose sum is greater than or equal to target. If there...
leetcodemediumarraysliding-windowbinary-searchprefix-sum

[Hard] 862. Shortest Subarray with Sum at Least K

Given an integer array nums and an integer k, return the length of the shortest non-empty subarray of nums with a sum of at least k. If there is no...
leetcodehardarraysliding-windowdequeprefix-summonotonic-deque

[Easy] 27. Remove Element

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of...
leetcodeeasyarraytwo-pointers

[Medium] 354. Russian Doll Envelopes

You are given a 2D array of integers envelopes where envelopes[i] = [wi, hi] represents the width and the height of an envelope.
leetcodemediumarraydynamic-programmingbinary-searchsorting

[Medium] 213. House Robber II

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a...
leetcodemediumarraydynamic-programming

[Medium] 622. Design Circular Queue

Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle and...
leetcodemediumarraylinked-listdesignqueue

[Medium] 1233. Remove Sub-Folders from the Filesystem

Given a list of folders folder, return the folders after removing all sub-folders in those folders. You may return the answer in any order.
leetcodemediumarraystringtriesorting

[Medium] 1801. Number of Orders in the Backlog

You are given a 2D integer array orders, where orders[i] = [price_i, amount_i, orderType_i] denotes that amount_i orders have been placed of type orderType_i at price price_i. The orderType_i is:...
leetcodemediumarrayheappriority-queuesimulation

[Medium] 63. Unique Paths II

You are given an m x n integer array grid. There is a robot initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right...
leetcodemediumarraydynamic-programmingmatrix

[Medium] 498. Diagonal Traverse

Given an m x n matrix mat, return an array of all the elements of the matrix in a diagonal order.
leetcodemediumarraymatrixsimulation

[Medium] 189. Rotate Array

Given an integer array nums, rotate the array to the right by k steps, where k is non-negative.
leetcodemediumarray

Algorithm Templates: Search

This page collects ready-to-use C++ templates for every major binary search pattern you’ll encounter on LeetCode — from basic sorted-array lookup to rotated arrays, 2D matrices, and “search on the...
leetcodetemplatessearchbinary-search

[Hard] 327. Count of Range Sum

Given an integer array nums and two integers lower and upper, return the number of range sums that lie in [lower, upper] inclusive.
leetcodehardarraydivide-and-conquer

[Medium] 1701. Average Waiting Time

There is a restaurant with a single chef. You are given an array customers, where customers[i] = [arrival_i, time_i]:
leetcodemediumarraysimulation

[Easy] 645. Set Mismatch

You have a set of integers s, which originally contains all the numbers from 1 to n. Unfortunately, due to some error, one of the numbers in s got duplicated...
leetcodeeasyarrayhash-tablemath

[Easy] 409. Longest Palindrome

Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters.
leetcodeeasystringhash-tablegreedy

[Easy] 387. First Unique Character in a String

Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.
leetcodeeasystringhash-table

[Easy] 349. Intersection of Two Arrays

Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order....
leetcodeeasyarrayhash-table

[Easy] 226. Invert Binary Tree

Given the root of a binary tree, invert the tree, and return its root.
leetcodeeasytreedfs

[Easy] 1624. Largest Substring Between Two Equal Characters

Given a string s, return the length of the longest substring between two equal characters, excluding the two equal characters themselves. If no such substring exists, return -1.
leetcodeeasystringhash-table

[Easy] 112. Path Sum

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path...
leetcodeeasytreedfs

[Easy] 104. Maximum Depth of Binary Tree

Given the root of a binary tree, return its maximum depth — the number of nodes along the longest path from the root down to the farthest leaf.
leetcodeeasytreedfs

[Easy] 101. Symmetric Tree

Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
leetcodeeasytreedfs

[Easy] 100. Same Tree

Given the roots of two binary trees p and q, write a function to check if they are the same or not.
leetcodeeasytreedfs

[Easy] 409. Longest Palindrome

Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters.
leetcodeeasystringhash-tablegreedy

[Medium] 208. Implement Trie (Prefix Tree)

A trie (pronounced as “try”) or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of...
leetcodemediumstringdesigntrie

[Hard] 732. My Calendar III

A k-booking happens when k events have some non-empty intersection (i.e., there is some time that is common to all k events).
leetcodehardarraybinary-searchdesignsegment-treeordered-set

[Easy] 3110. Score of a String

You are given a string s. The score of a string is defined as the sum of the absolute difference between the ASCII values of adjacent characters.
leetcodeeasystringarray

[Medium] 729. My Calendar I

You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a double booking.
leetcodemediumarraybinary-searchdesignordered-set

[Hard] 315. Count of Smaller Numbers After Self

You are given an integer array nums and you have to return a new array counts. The array counts has the property where counts[i] is the number of smaller elements...
leetcodehardarraybinary-searchdivide-and-conquerbinary-indexed-treesegment-treemerge-sort

[Medium] 307. Range Sum Query - Mutable

Given an integer array nums, handle multiple queries of the following types:
leetcodemediumarraysegment-treebinary-indexed-tree

[Hard] 305. Number of Islands II

You are given an empty 2D binary grid grid of size m x n. The grid represents a map where 0’s represent water and 1’s represent land. Initially, all the...
leetcodehardarrayunion-findgraph

[Medium] 802. Find Eventual Safe States

There is a directed graph of n nodes with each node labeled from 0 to n - 1. The graph is represented by a 0-indexed 2D integer array graph where...
leetcodemediumgraphdfscycle-detection

[Hard] 315. Count of Smaller Numbers After Self

You are given an integer array nums and you have to return a new array counts. The array counts has the property where counts[i] is the number of smaller elements...
leetcodehardarraybinary-searchdivide-and-conquerbinary-indexed-treesegment-treemerge-sort

[Medium] 310. Minimum Height Trees

A tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.
leetcodemediumgraphtreetopological-sortbfs

[Hard] 269. Alien Dictionary

There is a new alien language that uses the English alphabet. However, the order among the letters is unknown to you.
leetcodehardgraphtopological-sortstring

[Medium] 79. Word Search

Given an m x n grid of characters board and a string word, return true if word exists in the grid.
leetcodemediumarraybacktrackingmatrixdfs

[Medium] 22. Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
leetcodemediumstringbacktrackingrecursion

[Hard] 51. N-Queens

The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.
leetcodehardarraybacktrackingrecursion

[Easy] 844. Backspace String Compare

Given two strings s and t, return true if they are equal when both are typed into empty text editors. '#' means a backspace character.
leetcodeeasystringtwo-pointersstack

[Medium] 721. Accounts Merge

Given a list of accounts where each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emails...
leetcodemediumarrayhash-tablestringunion-finddfs

[Medium] 64. Minimum Path Sum

Given a m x n grid filled with non-negative numbers, find a path from top-left to bottom-right, which minimizes the sum of all numbers along its path.
leetcodemediumarraydynamic-programmingmatrix

[Hard] 1340. Jump Game V

Given an array of integers arr and an integer d. In one step you can jump from index i to index:
leetcodehardarraydynamic-programmingdfsmemoization

[Medium] 692. Top K Frequent Words

Given an array of strings words and an integer k, return the k most frequent strings.
leetcodemediumhash-tableheapsortingstring

[Medium] 5. Longest Palindromic Substring

Given a string s, return the longest palindromic substring in s.
leetcodemediumstringtwo-pointersdynamic-programming

[Medium] 102. Binary Tree Level Order Traversal

Given the root of a binary tree, return the level order traversal of its nodes’ values. (i.e., from left to right, level by level).
leetcodemediumtreebfsbinary-tree

[Easy] 993. Cousins in Binary Tree

Given the root of a binary tree with unique values and the values of two different nodes of the tree x and y, return true if the nodes corresponding to...
leetcodeeasytreebfsbinary-tree

[Medium] 103. Binary Tree Zigzag Level Order Traversal

Given the root of a binary tree, return the zigzag level order traversal of its nodes’ values. (i.e., from left to right, then right to left for the next level...
leetcodemediumtreebfsbinary-tree

[Medium] 215. Kth Largest Element in an Array

Given an integer array nums and an integer k, return the kth largest element in the array.
leetcodemediumarrayheapquickselectdivide-and-conquer

Algorithm Templates: Heap

Welcome to the Heap templates page! Here you’ll find battle-tested C++ snippets for every common heap (priority queue) pattern on LeetCode — from basic min/max heaps to advanced techniques like...
leetcodetemplatesheappriority-queue

[Medium] 53. Maximum Subarray

Given an integer array nums, find the subarray with the largest sum, and return its sum.
leetcodemediumarraydynamic-programminggreedydivide-and-conquer

[Medium] 376. Wiggle Subsequence

A wiggle sequence is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative....
leetcodemediumarraydynamic-programminggreedy

[Medium] 1029. Two City Scheduling

A company is planning to interview 2n people. Given the array costs where costs[i] = [aCosti, bCosti], the cost of flying the i-th person to city a is aCosti, and...
leetcodemediumarraygreedysorting

[Hard] 135. Candy

There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings.
leetcodehardarraygreedy

[Easy] 1710. Maximum Units on a Truck

You are assigned to put some amount of boxes onto one truck. You are given a 2D array boxTypes, where boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]:
leetcodeeasyarraygreedysorting

[Easy] 561. Array Partition

Given an integer array nums of 2n integers, group these integers into n pairs (a1, b1), (a2, b2), ..., (an, bn) such that the sum of min(ai, bi) for all...
leetcodeeasyarraygreedysorting

[Easy] 392. Is Subsequence

Given two strings s and t, return true if s is a subsequence of t, or false otherwise.
leetcodeeasystringtwo-pointersgreedydynamic-programming

[Medium] 55. Jump Game

You are given an integer array nums. You are initially positioned at the array’s first index, and each element in the array represents your maximum jump length at that position....
leetcodemediumarraygreedydynamic-programming

[Medium] 452. Minimum Number of Arrows to Burst Balloons

There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D array points where points[i] = [xstart, xend] denotes a...
leetcodemediumarraygreedysortingintervals

[Medium] 435. Non-overlapping Intervals

Given an array of intervals intervals where intervals[i] = [starti, endi], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
leetcodemediumarraygreedysortingintervalsdynamic-programming

[Easy] 860. Lemonade Change

At a lemonade stand, each lemonade costs 5. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills)....
leetcodeeasyarraygreedysimulation

[Easy] 455. Assign Cookies

Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie.
leetcodeeasyarraygreedysortingtwo-pointers

[Medium] 351. Android Unlock Patterns

Android devices have a special lock screen with a 3 x 3 grid of dots. Users can set an “unlock pattern” by connecting the dots in a specific sequence, which...
leetcodemediumbacktrackingrecursiondynamic-programming

[Medium] 1177. Can Make Palindrome from Substring

You are given a string s and array queries where queries[i] = [left, right, k]. We may rearrange the substring s[left...right] and then choose up to k of its characters...
leetcodemediumstringbit-manipulationprefix-sumhash-table

[Medium] 393. UTF-8 Validation

Given an integer array data representing the data, return whether it is a valid UTF-8 encoding (i.e., it translates to a sequence of valid UTF-8 encoded characters).
leetcodemediumbit-manipulationstringarray

[Hard] 568. Maximum Vacation Days

LeetCode wants to give one of its best employees the option to travel among n cities to collect algorithm problems. But all work and no play makes Jack a dull...
leetcodeharddynamic-programminggraphoptimization

[Medium] 418. Sentence Screen Fitting

Given a rows x cols screen and a sentence represented as a list of strings, return the number of times the given sentence can be fitted on the screen.
leetcodemediumdynamic-programmingstringsimulation

[Easy] 496. Next Greater Element I

The next greater element of some element x in an array is the first greater element that is to the right of x in the same array.
leetcodeeasyarraystackmonotonic-stackhash-table

[Medium] 360. Sort Transformed Array

Given a sorted integer array nums and three integers a, b, and c, apply a quadratic function f(x) = ax² + bx + c to each element nums[i] in the...
leetcodemediumarraytwo-pointersmathparabola

[Hard] 715. Range Module

A Range Module is a module that tracks ranges of numbers. Design a data structure to track the ranges represented as half-open intervals [left, right).
leetcodeharddesigndata-structuresintervalmaptree-map

[Hard] 425. Word Squares

A word square is a sequence of words where the k-th row and k-th column read the same string.
leetcodehardbacktrackingtrierecursionstring

[Easy] 270. Closest Binary Search Tree Value

Given the root of a binary search tree and a target value, return the value in the BST that is closest to the target. If there are multiple answers, print...
leetcodeeasybinary-search-treetreerecursionbinary-search

[Hard] 685. Redundant Connection II

In this problem, a rooted tree is a directed graph such that there is exactly one node (the root) for which all other nodes are descendants of this node, plus...
leetcodehardunion-finddsugraphcycle-detectiondirected-graph

[Medium] 285. Inorder Successor in BST

Given the root of a binary search tree (BST) and a node p in it, return the in-order successor of that node in the BST. If the given node has...
leetcodemediumbinary-search-treetreeinorder-traversal

[Medium] 487. Max Consecutive Ones II

Given a binary array nums, return the maximum number of consecutive 1’s in the array if you can flip at most one 0.
leetcodemediumarraydynamic-programmingsliding-window

[Easy] 661. Image Smoother

An image smoother is a filter of the size 3 x 3 that can be applied to each cell of an image by rounding down the average of the cell...
leetcodeeasymatrixarraysimulation

[Medium] 616. Add Bold Tag in String

You are given a string s and an array of strings words. You should add a closed pair of bold tag <b> and </b> to wrap the substrings in s...
leetcodemediumstringarraygreedy

[Medium] 681. Next Closest Time

Given a time represented in the format "HH:MM", form the next closest time by reusing the current digits. There is no limit on how many times a digit can be...
leetcodemediumstringsimulationbrute-force

[Medium] 683. K Empty Slots

You have n bulbs in a row numbered from 1 to n. Initially, all the bulbs are turned off. On day i (for i from 0 to n-1), we turn...
leetcodemediumsliding-windowtwo-pointersarray

[Medium] 686. Repeated String Match

Given two strings a and b, return the minimum number of times you should repeat string a so that string b is a substring of it. If it is impossible...
leetcodemediumstring-matchingkmprabin-karprolling-hash

[Medium] 684. Redundant Connection

In this problem, a tree is an undirected graph that is connected and has no cycles.
leetcodemediumunion-finddsugraphcycle-detectiondfs

[Medium] 1976. Number of Ways to Arrive at Destination

You are in a city that consists of n intersections numbered from 0 to n - 1 with bi-directional roads between some intersections. The inputs are generated such that you...
leetcodemediumdijkstrashortest-pathgraphdynamic-programming

[Medium] 547. Number of Provinces

There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city...
leetcodealgorithmmediumcppdisjoint-setdfsgraphproblem-solving

[Medium] 399. Evaluate Division

You are given an array of variable pairs equations and an array of real numbers values, where equations[i] = [Ai, Bi] and values[i] represent the equation Ai / Bi =...
leetcodealgorithmmediumcppdisjoint-setgraphdfsproblem-solving

[Medium] 690. Employee Importance

You have a data structure of employee information, including the employee’s unique ID, importance value, and direct subordinates’ IDs.
leetcodealgorithmmediumcppdfsbfshash-tableproblem-solving

[Hard] 850. Rectangle Area II

You are given a 2D array of axis-aligned rectangles. For each rectangle[i] = [xi1, yi1, xi2, yi2], where (xi1, yi1) is the bottom-left corner and (xi2, yi2) is the top-right...
leetcodealgorithmhardcppgeometrysweep-linesegment-treeproblem-solving

[Medium] 286. Walls and Gates

You are given an m x n grid rooms initialized with these three possible values:
leetcodealgorithmmediumcpparraymatrixbfsproblem-solving

[Medium] 279. Perfect Squares

Given an integer n, return the least number of perfect square numbers that sum to n.
leetcodealgorithmmediumcppmathdynamic-programmingbfsproblem-solving

Algorithm Templates: Greedy

Greedy algorithms are among the most elegant tools in competitive programming — when they work, they’re simpler and faster than dynamic programming. This guide covers the core greedy patterns you’ll...
leetcodetemplatesgreedy

[Easy] 346. Moving Average from Data Stream

Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
leetcodealgorithmeasycppqueuesliding-windowdesignproblem-solving

[Medium] 994. Rotting Oranges

You are given an m x n grid where each cell can have one of three values:
leetcodealgorithmmediumcpparraymatrixbfsproblem-solving

[Medium] 253. Meeting Rooms II

Given an array of meeting time intervals intervals where intervals[i] = [starti, endi], return the minimum number of conference rooms required.
leetcodealgorithmmediumcpparraysortingpriority-queuetwo-pointersproblem-solving

[Easy] 67. Add Binary

Given two binary strings a and b, return their sum as a binary string.
leetcodealgorithmeasycppstringmathbit-manipulationproblem-solving

[Medium] 281. Zigzag Iterator

Given two 1d vectors, implement an iterator to return their elements alternately.
leetcodealgorithmmediumcppdesigniteratorproblem-solving

[Hard] 1206. Design Skiplist

Design a Skiplist without using any built-in libraries.
leetcodealgorithmhardcppdata-structuresskiplistlinked-listproblem-solving

[Medium] 75. Sort Colors

Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order...
leetcodealgorithmmediumcpparraytwo-pointerssortingproblem-solving

[Medium] 593. Valid Square

Given the coordinates of four points in 2D space p1, p2, p3, and p4, return true if the four points construct a square.
leetcodealgorithmmediumcppmathgeometryproblem-solving

[Medium] 146. LRU Cache

Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.
leetcodealgorithmmediumcppdesigndata-structureshash-maplinked-listproblem-solving

[Medium] 146. LRU Cache

Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.
leetcodealgorithmmediumcppdesigndata-structureshash-maplinked-listproblem-solving

[Medium] 983. Minimum Cost For Tickets

You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array days. Each day is...
leetcodealgorithmmediumcppdynamic-programmingproblem-solving

[Medium] 647. Palindromic Substrings

Given a string s, return the number of palindromic substrings in it.
leetcodealgorithmmediumcppstringtwo-pointersproblem-solving

[Medium] 56. Merge Intervals

Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input....
leetcodealgorithmmediumcpparraysortingintervalproblem-solving

[Medium] 528. Random Pick with Weight

You are given a 0-indexed array of positive integers w where w[i] describes the weight of the ith index.
leetcodealgorithmmediumcppdesignbinary-searchprefix-sumproblem-solving

[Medium] 398. Random Pick Index

Given an integer array nums with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array....
leetcodealgorithmmediumcpphash-tablereservoir-samplingproblem-solving

[Medium] 277. Find the Celebrity

Suppose you are at a party with n people (labeled from 0 to n - 1) and among them, there may exist one celebrity. The definition of a celebrity is...
leetcodealgorithmmediumcppgraphtwo-pointersproblem-solving

[Medium] 1762. Buildings With an Ocean View

There are n buildings in a line. You are given an integer array heights of size n that represents the heights of the buildings in the line.
leetcodealgorithmmediumcpparraystackmonotonic-stackproblem-solving

[Medium] 129. Sum Root to Leaf Numbers

You are given the root of a binary tree containing digits from 0 to 9 only.
leetcodealgorithmmediumcpptreedfsproblem-solving

[Medium] 1209. Remove All Adjacent Duplicates in String II

You are given a string s and an integer k, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them, causing the left...
leetcodealgorithmmediumcppstringstacktwo-pointersproblem-solving

[Hard] 489. Robot Room Cleaner

Given a robot cleaner in a room modeled as a grid.
leetcodealgorithmhardcppdfsbacktrackingproblem-solving

[Hard] 32. Longest Valid Parentheses

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
leetcodealgorithmhardcppstringdynamic-programmingstackproblem-solving

[Easy] 938. Range Sum of BST

Given the root node of a binary search tree and two integers low and high, return the sum of values of all nodes with a value in the inclusive range...
leetcodealgorithmeasycpptreebstdfsproblem-solving

[Easy] 408. Valid Word Abbreviation

A string can be abbreviated by replacing any number of non-adjacent, non-empty substrings with their lengths. The lengths should not have leading zeros.
leetcodealgorithmeasycppstringtwo-pointersproblem-solving

[Easy] 1047. Remove All Adjacent Duplicates In String

You are given a string s consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them.
leetcodealgorithmeasycppstringstacktwo-pointersproblem-solving

Algorithm Templates: String Processing

Welcome to the String Processing template collection! These are ready-to-use C++ snippets for the core string patterns: sliding window, two pointers, string matching, manipulation, and parsing. If you already know...
leetcodetemplatesstring

Algorithm Templates: Queue

Queues are one of the most versatile data structures in algorithm problems. This page collects ready-to-use C++ templates for every queue variant you’ll encounter on LeetCode — from the basic...
leetcodetemplatesqueue

Algorithm Templates: Math & Bit Manipulation

This page collects ready-to-use C++ templates for bit manipulation, fast exponentiation, GCD/LCM, prime sieves, and basic number theory. Each snippet is self-contained — copy it into your solution and adapt...
leetcodetemplatesmathbit-manipulation

Algorithm Templates: Linked List

This page collects battle-tested C++ templates for every major linked-list pattern you’ll see on LeetCode. Each section includes ready-to-use code, the signal phrases that tell you which pattern to reach...
leetcodetemplateslinked-list

Algorithm Templates: DFS

Depth-First Search (DFS) is one of the most fundamental graph traversal algorithms. It works by starting at a node and exploring as far down each branch as possible before backtracking...
leetcodetemplatesdfsgraph

Algorithm Templates: Data Structure Design

Data structure design problems are among the most popular interview questions at top tech companies. This page provides complete, tested C++ implementations for LRU/LFU cache, Trie, time-based key-value store, and...
leetcodetemplatesdesign

Algorithm Templates: BFS

Breadth-First Search (BFS) is a graph traversal algorithm that explores nodes layer by layer, visiting all neighbors at the current depth before moving deeper. It’s the go-to technique for finding...
leetcodetemplatesbfsgraph

Algorithm Templates: Backtracking

Welcome to the backtracking templates! Backtracking is one of the most versatile problem-solving techniques in competitive programming—once you learn the core pattern, you can tackle a huge family of problems...
leetcodetemplatesbacktracking

Algorithm Templates: Array & Matrix

Welcome to the Array & Matrix template collection! These are ready-to-use C++ snippets for the most common array patterns: two pointers, sliding window, prefix sum, binary search, and matrix operations....
leetcodetemplatesarraymatrix

[Medium] 200. Number of Islands

Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.
leetcodealgorithmmediumcppdfsgraphmatrixproblem-solving

[Medium] 969. Pancake Sorting

Given an array of integers arr, sort the array by performing a series of pancake flips.
leetcodealgorithmmediumcpparraysortingproblem-solving

[Medium] 49. Group Anagrams

Given an array of strings strs, group the anagrams together. You can return the answer in any order.
leetcodealgorithmmediumcppstringhash-tableproblem-solving

[Medium] 45. Jump Game II

You are given a 0-indexed array of integers nums of length n. You are initially positioned at nums[0].
leetcodealgorithmmediumcpparraygreedyproblem-solving

[Medium] 2. Add Two Numbers

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two...
leetcodealgorithmmediumcpplinked-listrecursionproblem-solving

[Medium] 198. House Robber

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. The only constraint stopping you from robbing each of...
leetcodealgorithmmediumcppdynamic-programmingdpproblem-solving

[Easy] 509. Fibonacci Number

The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1....
leetcodealgorithmeasycppdynamic-programmingrecursionproblem-solving

[Easy] 203. Remove Linked List Elements

Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.
leetcodealgorithmeasycpplinked-listiterationproblem-solving

[Medium] 1424. Diagonal Traverse II

Given a 2D integer array nums, return all elements of nums in diagonal order.
leetcodealgorithmmediumcpparraymatrixhash-mapbfsproblem-solving

[Easy] 206. Reverse Linked List

Given the head of a singly linked list, reverse the list, and return the reversed list.
leetcodealgorithmeasycpplinked-listrecursioniterationproblem-solving

[Medium] 146. LRU Cache

Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.
leetcodealgorithmmediumcppdesigndata-structureshash-maplinked-listproblem-solving

[Medium] 93. Restore IP Addresses

A valid IP address consists of exactly four integers separated by single dots. Each integer is between 0 and 255 (inclusive) and cannot have leading zeros.
leetcodealgorithmmediumcppbacktrackingstringproblem-solving

[Hard] 460. LFU Cache

Design and implement a data structure for a Least Frequently Used (LFU) cache.
leetcodealgorithmhardcppdesigndata-structureshash-maplinked-listproblem-solving

Algorithm Templates: Stack

The stack is one of the most versatile data structures in coding interviews. Whether you’re matching parentheses, evaluating expressions, or finding the next greater element in an array, a stack...
leetcodetemplatesstackdata-structures

Algorithm Templates: Calculator

Minimal, copy-paste C++ for expression evaluation with +, −, ×, ÷ and parentheses. See also Stack for RPN and nested expressions.
leetcodetemplatescalculatorexpression-evaluation

[Medium] 224. Basic Calculator

Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation.
leetcodealgorithmmediumcppstringstackexpression-evaluationproblem-solving

[Hard] 772. Basic Calculator III

Implement a basic calculator to evaluate a simple expression string.
leetcodealgorithmhardcppstringstackrecursionexpression-evaluationproblem-solving

[Medium] 227. Basic Calculator II

Given a string s which represents an expression, evaluate this expression and return its value.
leetcodealgorithmmediumcppstringstackexpression-evaluationproblem-solving

[Medium] 324. Wiggle Sort II

Rearrange nums such that nums[0] < nums[1] > nums[2] < nums[3] ... (wiggle order).
leetcodealgorithmmediumcpparraysnth-elementthree-way-partitionindex-mappingproblem-solving

[Easy] 20. Valid Parentheses

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
leetcodealgorithmeasycppstringstackproblem-solving

[Medium] 525. Contiguous Array

Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0 and 1.
leetcodealgorithmmediumcpparrayshash-mapprefix-sumproblem-solving

[Hard] 480. Sliding Window Median

The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean...
leetcodealgorithmhardcpparraysmultisetsliding-windowtwo-heapsproblem-solving

[Hard] 239. Sliding Window Maximum

You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right....
leetcodealgorithmhardcpparraysdequesliding-windowmonotonic-queueproblem-solving

[Easy] 485. Max Consecutive Ones

Given a binary array nums, return the maximum number of consecutive 1’s in the array.
leetcodealgorithmeasycpparrayssliding-windowproblem-solving

[Medium] 18. 4Sum

Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that:
leetcodealgorithmmediumcpparraystwo-pointerssortingproblem-solving

Algorithm Templates: Trees

Trees are one of the most frequently tested data structures in coding interviews. This page collects ready-to-use C++ templates for every major tree pattern — from basic traversals to advanced...
leetcodetemplatestrees

Algorithm Templates: Math & Geometry

Minimal, copy-paste C++ for combinatorics (nCk mod P) and 2D geometry primitives (cross product, point on segment).
leetcodetemplatesmathgeometry

Algorithm Templates: Graph

Graph algorithms are among the most versatile tools in competitive programming and coding interviews. A graph is simply a collection of nodes (vertices) connected by edges, and nearly every “network,”...
leetcodetemplatesgraph

Algorithm Templates: Dynamic Programming

Dynamic Programming is the most common pattern in LeetCode Medium/Hard problems. If you only learn one advanced technique, make it DP.
leetcodetemplatesdynamic-programming

Algorithm Templates: Data Structures & Core Algorithms

This page is your toolbox of essential data structures for LeetCode. Each template is self-contained C++ you can copy directly into your solution. They range from beginner-friendly (binary search, prefix...
leetcodetemplatesdata-structuresalgorithms

Algorithm Templates: Arrays & Strings

Arrays and strings are the foundation of coding interviews — you’ll encounter them in nearly every problem set. This page provides battle-tested C++ templates for the most important patterns: sliding...
leetcodetemplatesarraysstrings

Algorithm Templates: Advanced Techniques

This page covers specialized algorithmic techniques that appear in Hard-level LeetCode problems and competitive programming. These are not everyday patterns — most interviews won’t require them — but when a...
leetcodetemplatesadvanced

[Easy] 717. 1-bit and 2-bit Characters

Given a binary array bits that ends with 0, determine whether the last character must be a 1-bit character.
leetcodeeasyarrayparsing

[Easy] 344. Reverse String

Reverse the array of characters s in-place using O(1) extra memory.
leetcodeeasytwo-pointersstring

[Medium] 636. Exclusive Time of Functions

Difficulty: Medium Category: Stack, Parsing, Simulation Companies: Amazon, Facebook, Google, Twitter
leetcodemediumstackparsing

[Medium] 1094. Car Pooling

Difficulty: Medium Category: Array, Sorting, Simulation Companies: Amazon, Google, Microsoft, Uber
leetcodemediumarraysorting

[Medium] 348. Design Tic-Tac-Toe

Difficulty: Medium Category: Design, Array, Matrix Companies: Amazon, Google, Microsoft, Facebook
leetcodemediumdesignarray

[Medium] 419. Battleships in a Board

Difficulty: Medium Category: Array, Matrix, DFS Companies: Amazon, Google, Microsoft
leetcodemediumarraymatrix

[Medium] 545. Boundary of Binary Tree

Difficulty: Medium Category: Tree, DFS, Binary Tree Companies: Amazon, Google, Facebook, Microsoft
leetcodemediumtreedfs

[Medium] 347. Top K Frequent Elements

Difficulty: Medium Category: Array, Hash Table, Heap, Bucket Sort, Quickselect Companies: Amazon, Google, Facebook, Microsoft, Apple
leetcodemediumarrayhash-tableheap

[Medium] 973. K Closest Points to Origin

Difficulty: Medium Category: Array, Sorting, Heap, Quickselect Companies: Amazon, Google, Facebook, Microsoft
leetcodemediumarraysorting

[Medium] 207. Course Schedule

There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates...
leetcodemediumgraphtopological-sortcycle-detection

[Medium] 752. Open the Lock

You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can...
leetcodemediumbfsshortest-pathlock

[Medium] 322. Coin Change

You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.
leetcodemediumdynamic-programmingdpcoin-change

[Medium] 47. Permutations II

Difficulty: Medium Category: Backtracking, Recursion, Duplicates
leetcodealgorithmmediumbacktrackingrecursionduplicates

[Medium] 77. Combinations

Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n].
leetcodemediumbacktrackingrecursioncombinations

[Medium] 46. Permutations

Difficulty: Medium Category: Backtracking, Recursion
leetcodealgorithmmediumbacktrackingrecursion

[Medium] 1865. Finding Pairs With a Certain Sum

You are given two integer arrays nums1 and nums2. You are tasked to implement a data structure that supports the following operations:
leetcodealgorithmmediumcpphash-mapdata-structureproblem-solving

[Medium] 437. Path Sum III

Given the root of a binary tree and an integer targetSum, return the number of paths where the sum of the values along the path equals targetSum.
leetcodealgorithmmediumcpptreedfsrecursionproblem-solving

[Medium] 394. Decode String

Given an encoded string, return its decoded string.
leetcodealgorithmmediumcppstackstring-processingproblem-solving

[Medium] 417. Pacific Atlantic Water Flow

There is an m x n rectangular island that borders both the Pacific Ocean and the Atlantic Ocean. The Pacific Ocean touches the island’s left and top edges, and the...
leetcodealgorithmmediumcppdfsbfsgraphproblem-solving

[Medium] 406. Queue Reconstruction by Height

You are given an array of people, people, which are the attributes of some people in a queue (not necessarily in order). Each people[i] = [hi, ki] represents the ith...
leetcodealgorithmmediumcppgreedysortinglistproblem-solving

[Medium] 1856. Maximum Sum of Minimum Product

The minimum product of a subarray is the minimum value in the subarray multiplied by the sum of the subarray.
leetcodealgorithmmediumcppstackmonotonic-stackprefix-sumproblem-solving

[Medium] 316. Remove Duplicate Letters

Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all...
leetcodealgorithmmediumcppstackmonotonic-stackgreedyproblem-solving

[Medium] 648. Replace Words

In English, we have a concept called root, which can be followed by some other word to form another longer word. Let’s call this word successor. For example, when the...
leetcodealgorithmmediumcpptriehash-setstring-processingproblem-solving

[Medium] 503. Next Greater Element II

Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0]), return the next greater number for every element in nums.
leetcodealgorithmmediumcppmonotonic-stackstackproblem-solving

[Medium] 2466. Count Ways To Build Good Strings

Given the integers zero, one, low, and high, we can construct a string by starting with an empty string, and then at each step perform either of the following:
leetcodealgorithmmediumcppdynamic-programmingdpproblem-solving

[Medium] 494. Target Sum

You are given an integer array nums and an integer target.
leetcodealgorithmmediumcppdynamic-programmingdpsubset-sumproblem-solving

[Medium] 240. Search a 2D Matrix II

Write an efficient algorithm that searches for a value target in an m x n integer matrix. This matrix has the following properties:
leetcodealgorithmmediumcppbinary-searchmatrix2d-arraydivide-conquersearchoptimizationproblem-solving

[Medium] 912. Sort an Array

Given an array of integers nums, sort the array in ascending order and return it.
leetcodealgorithmmediumcppsortingmerge-sortheap-sortcounting-sortdata-structuresdivide-conquerproblem-solving

[Hard] 218. The Skyline Problem

A city’s skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all...
leetcodealgorithmhardcppsweep-linepriority-queuedata-structuresunion-findproblem-solving

[Medium] 990. Satisfiability of Equality Equations

You are given an array of strings equations that represent relationships between variables. Each string equations[i] is of length 4 and takes one of two different forms: "xi==yi" or "xi!=yi"....
leetcodealgorithmdata-structuresdisjoint-setgraphdfsmediumcppconnected-componentsgraph-coloringproblem-solving

[Medium] 96. Unique Binary Search Trees

Given an integer n, return the number of structurally unique BST’s (binary search trees) that have exactly n nodes with values from 1 to n.
leetcodealgorithmdynamic-programmingdata-structuresmathcatalan-numbersmediumcppbinary-search-treesproblem-solving

[Medium] 131. Palindrome Partitioning

Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s.
leetcodealgorithmbacktrackingdata-structuresstringpalindromerecursionmediumcpppartitioningproblem-solving

[Medium] 77. Combinations

This is a classic backtracking problem that requires generating all possible combinations of k numbers chosen from the range [1, n]. The key insight is using DFS with backtracking to...
leetcodealgorithmbacktrackingdata-structuresrecursionmediumcppcombinationsdfsproblem-solving

[Medium] 89. Gray Code

An n-bit gray code sequence is a sequence of 2^n integers where:
leetcodealgorithmbacktrackingdata-structuresrecursionbit-manipulationmediumcppgray-codeproblem-solving

[Medium] 54. Spiral Matrix

Given an m x n matrix, return all elements of the matrix in spiral order.
leetcodealgorithmmatrixdata-structuressimulationtraversalmediumcppspiral-matrixproblem-solving

[Medium] 50. Pow(x, n)

Implement pow(x, n), which calculates x raised to the power n (i.e., x^n).
leetcodealgorithmmathdata-structuresrecursionbit-manipulationmediumcpppowproblem-solving

[Medium] 62. Unique Paths

This is a classic dynamic programming problem that requires finding the number of unique paths from top-left to bottom-right of a grid. The key insight is recognizing the overlapping subproblems...
leetcodealgorithmdynamic-programmingdata-structuresgridcombinatoricsmediumcppunique-pathsproblem-solving

[Hard] 25. Reverse Nodes in k-Group

This is a complex linked list problem that requires reversing nodes in groups of k. The key insight is using recursion to handle the grouping and a helper function to...
leetcodealgorithmlinked-listrecursivedata-structurespointershardcppreverse-nodesk-grouprecursionproblem-solving

[Medium] 48. Rotate Image

This is a matrix manipulation problem that requires rotating a 2D matrix 90 degrees clockwise in-place. The key insight is understanding the relationship between matrix positions during rotation and implementing...
leetcodealgorithmmatrixdata-structures2d-arraytransformationmediumcpprotate-imagein-placeproblem-solving

[Medium] 150. Evaluate Reverse Polish Notation

This is a classic stack problem that requires evaluating mathematical expressions written in Reverse Polish Notation (RPN). The key insight is using a stack to process operands and operators in...
leetcodealgorithmstackdata-structuresmathematical-expressionmediumcppreverse-polish-notationrpnproblem-solving

[Medium] 1242. Web Crawler Multithreaded

This is a multithreading problem that requires implementing a concurrent web crawler. The key insight is using proper synchronization mechanisms to avoid race conditions while crawling URLs from the same...
leetcodealgorithmmultithreadingconcurrencydata-structuressynchronizationmediumcppweb-crawlerconcurrent-programmingproblem-solving

[Medium] 794. Valid Tic-Tac-Toe State

This is a simulation problem that requires understanding the rules of Tic-Tac-Toe and validating whether a given board state is possible. The key insight is checking the count of X’s...
leetcodealgorithmsimulationdata-structuresgame-logicvalidationmediumcpptic-tac-toegame-validationproblem-solving

Meta‑Style LeetCode Question List

Meta‑Style LeetCode Question List
leetcodealgorithmmetainterview-preparationpractice-listfaangcoding-interviewproblem-solvingcompetitive-programmingdata-structures

Hash Table Mastery List

🧩 Hash Table Mastery List
leetcodealgorithmhashdata-structuresinterview-preparationpractice-listhash-tablehash-mapproblem-solvingcompetitive-programming

LeetCode Linked List Mastery List

LeetCode Linked List Mastery List
leetcodealgorithmlinked-listdata-structuresinterview-preparationpractice-listproblem-solvingcompetitive-programmingpointerstraversal

[Medium] 24. Swap Nodes in Pairs

This is a classic linked list problem that requires understanding how to manipulate pointers and traverse linked lists. The key insight is understanding pointer manipulation, recursion, and iterative approaches with...
leetcodealgorithmlinked-listrecursivedata-structurespointersmediumcppswap-nodesrecursioniterativeproblem-solving

C++ STL Quick Reference for LeetCode

📚 C++ STL Quick Reference for LeetCode
leetcodealgorithmcppdata-structuresreferencecheat-sheetprogrammingstlcontainersiteratorsalgorithmscompetitive-programming

[Medium] 33. Search in Rotated Sorted Array

There is an integer array nums sorted in ascending order (with distinct values), rotated at an unknown pivot. Given nums and target, return the index of target or -1 if...
leetcodemediumbinary-searcharray
← Back to Home