brain

tamnd's digital brain — notes, problems, research

43815 notes

LeetCode 1104 - Path In Zigzag Labelled Binary Tree

This problem describes an infinite binary tree where nodes are normally arranged level by level, but with a twist in how labels are assigned. In a standard binary tree, nodes in each level are labeled from left to right.

leetcodemediummathtreebinary-tree
LeetCode 789 - Escape The Ghosts

This problem takes place on an infinite two dimensional grid. You begin at coordinate (0, 0) and want to reach a destination called target. At the same time, several ghosts also move on the grid from their own starting positions.

leetcodemediumarraymath
LeetCode 1621 - Number of Sets of K Non-Overlapping Line Segments

This guide is quite large and highly detailed under your required structure, especially with full worked examples, both

leetcodemediummathdynamic-programmingcombinatoricsprefix-sum
LeetCode 561 - Array Partition

The problem gives an array nums containing 2n integers. Our task is to divide these integers into exactly n pairs. For each pair (ai, bi), we take the smaller value, min(ai, bi). After computing the minimum value from every pair, we sum all of those minimums together.

leetcodeeasyarraygreedysortingcounting-sort
LeetCode 1143 - Longest Common Subsequence

The problem asks us to find the length of the longest subsequence that appears in both input strings. A subsequence is formed by deleting some characters from a string while keeping the remaining characters in the same relative order. The characters do not need to be contiguous.

leetcodemediumstringdynamic-programming
LeetCode 528 - Random Pick with Weight

The problem asks us to design a data structure that supports weighted random sampling. You are given an array w, where each element represents the weight of an index. Instead of choosing every index with equal probability, the selection probability depends on its weight.

leetcodemediumarraymathbinary-searchprefix-sumrandomized
LeetCode 784 - Letter Case Permutation

The problem asks us to generate every possible string that can be formed by independently changing the case of each alphabetic character in the input string. Digits cannot be modified, so they always remain the same in every generated result.

leetcodemediumstringbacktrackingbit-manipulation
LeetCode 917 - Reverse Only Letters

The problem asks us to reverse only the English letters in a string while keeping all non-letter characters fixed in their original positions. In other words, letters move, but symbols, digits, and punctuation marks stay exactly where they started.

leetcodeeasytwo-pointersstring
LeetCode 575 - Distribute Candies

This problem asks us to maximize the number of distinct candy types Alice can eat while respecting a strict limit on how many candies she is allowed to consume. We are given an integer array candyType, where each element represents the type of a candy.

leetcodeeasyarrayhash-table
LeetCode 986 - Interval List Intersections

The problem gives us two lists of closed intervals. Each interval is represented as [start, end], meaning every value from start through end, inclusive, belongs to that interval.

leetcodemediumarraytwo-pointerssweep-line
LeetCode 1467 - Probability of a Two Boxes Having The Same Number of Distinct Balls

The problem gives us several colors of balls, where balls[i] represents how many balls exist for color i. The total numb

leetcodehardarraymathdynamic-programmingbacktrackingcombinatoricsprobability-and-statistics
LeetCode 50 - Pow(x, n)

The problem asks us to implement exponentiation manually, specifically computing: where x is a floating point number and n is an integer exponent. The input consists of two values: - x, the base - n, the exponent The output should be the result of raising x to the power n.

leetcodemediummathrecursion
LeetCode 1772 - Sort Features by Popularity

This problem asks us to determine the popularity of product features based on user survey responses. We are given a list of features where each element is a single-word feature name, and a list of responses where each element is a string of space-separated words that users…

leetcodemediumarrayhash-tablestringsorting
LeetCode 1811 - Find Interview Candidates

The problem is asking us to identify users who qualify as interview candidates based on their performance in LeetCode contests. We are provided two tables: Contests and Users.

leetcodemediumdatabase
LeetCode 1068 - Product Sales Analysis I

This problem asks us to combine information from two database tables, Sales and Product, and produce a result containing the product name, the year of the sale, and the sale price for every sale record. The Sales table stores transactional information.

leetcodeeasydatabase
LeetCode 926 - Flip String to Monotone Increasing

The problem asks us to transform a binary string into a monotone increasing string using the minimum number of character flips. A binary string is considered monotone increasing if all 0s appear before all 1s. In other words, once a 1 appears, no 0 can appear after it.

leetcodemediumstringdynamic-programming
CF 82D - Two out of Three

We are asked to simulate a queue of customers, where each customer has a known service time. The cashier can serve two people simultaneously, and the time to serve two people at once is the maximum of their individual times.

codeforcescompetitive-programmingdp
LeetCode 981 - Time Based Key-Value Store

The problem asks us to design a data structure that behaves like a key-value store, but with an important twist: the same key can have multiple values over time.

leetcodemediumhash-tablestringbinary-searchdesign
LeetCode 278 - First Bad Version

The problem gives us a sequence of product versions numbered from 1 to n. At some point, one version becomes bad, and every version after it is also bad.

leetcodeeasybinary-searchinteractive
LeetCode 41 - First Missing Positive

The problem asks us to find the smallest positive integer that does not appear in an unsorted integer array. The key detail is that we only care about positive integers starting from 1.

leetcodehardarrayhash-table
LeetCode 697 - Degree of an Array

The problem asks us to find the shortest contiguous subarray of an array nums that has the same degree as the original array. The degree of an array is defined as the maximum frequency of any element in that array.

leetcodeeasyarrayhash-table
LeetCode 393 - UTF-8 Validation

The problem asks us to determine whether a sequence of integers represents a valid UTF-8 encoded byte stream. Each integer in the input array represents one byte, meaning only its lowest 8 bits matter.

leetcodemediumarraybit-manipulation
LeetCode 876 - Middle of the Linked List

The problem gives us the head of a singly linked list and asks us to return the middle node. A singly linked list is a sequence of nodes where each node contains a value and a pointer to the next node.

leetcodeeasylinked-listtwo-pointers
LeetCode 804 - Unique Morse Code Words

The problem asks us to determine how many unique Morse code transformations exist among a list of words. Each lowercase English letter maps to a specific Morse code representation.

leetcodeeasyarrayhash-tablestring
LeetCode 1331 - Rank Transform of an Array

The problem asks us to replace every number in the input array with its rank when the array is sorted in ascending order.

leetcodeeasyarrayhash-tablesorting
CF 64I - Sort the Table

We are given a table where every row contains several string fields, and the first input line tells us the name of each column. Another line describes how the rows should be ordered. Each rule has the form COLUMNNAME ASC or COLUMNNAME DESC.

codeforcescompetitive-programming*specialsortings
LeetCode 1836 - Remove Duplicates From an Unsorted Linked List

This problem gives us the head of a singly linked list whose values are not sorted. Our task is to remove every node whose value appears more than once anywhere in the list. The important detail is that we are not removing duplicate occurrences while keeping one copy.

leetcodemediumhash-tablelinked-list
CF 35E - Parade

Each skyscraper is an axis-aligned rectangle sitting on the ground. A building with parameters (h, l, r) occupies every point with l ≤ x ≤ r and 0 ≤ y ≤ h.

codeforcescompetitive-programmingdata-structuressortings
LeetCode 1173 - Immediate Food Delivery I

The problem is asking to calculate the percentage of immediate food deliveries from a delivery table. An immediate delivery is defined as one where the customerprefdeliverydate matches the orderdate.

leetcodeeasydatabase
LeetCode 1511 - Customer Order Frequency

This problem asks us to identify customers who consistently spend at least $100 in each of two consecutive months, June and July of 2020.

leetcodeeasydatabase
LeetCode 1352 - Product of the Last K Numbers

This problem asks us to design a data structure that continuously processes a stream of integers and supports querying t

leetcodemediumarraymathdesigndata-streamprefix-sum
LeetCode 1671 - Minimum Number of Removals to Make Mountain Array

This problem asks us to remove the minimum number of elements from an array so that the remaining elements form a valid

leetcodehardarraybinary-searchdynamic-programminggreedy
LeetCode 1216 - Valid Palindrome III

The problem asks us to determine whether a given string s can become a palindrome after removing at most k characters. A palindrome is a string that reads the same forwards and backwards, and a k-palindrome is one that can be turned into a palindrome with at most k deletions.

leetcodehardstringdynamic-programming
LeetCode 521 - Longest Uncommon Subsequence I

The problem asks us to find the length of the longest uncommon subsequence between two strings a and b. To understand the problem clearly, we first need to understand what an uncommon subsequence means.

leetcodeeasystring
LeetCode 1215 - Stepping Numbers

The problem is asking us to find all integers within a given range [low, high] that are stepping numbers. A stepping number is defined as a number in which the absolute difference between every pair of adjacent digits is exactly 1.

leetcodemediummathbacktrackingbreadth-first-search
LeetCode 421 - Maximum XOR of Two Numbers in an Array

The problem gives us an array of non-negative integers called nums. We must choose two indices i and j such that 0 <= i <= j < n, then compute: The goal is to return the largest XOR value that can be produced from any pair in the array.

leetcodemediumarrayhash-tablebit-manipulationtrie
LeetCode 755 - Pour Water

This problem asks us to simulate how water droplets behave when poured onto a one-dimensional terrain. The terrain is represented by the array heights, where each element describes the height of a column at that position.

leetcodemediumarraysimulation
LeetCode 245 - Shortest Word Distance III

The problem gives us an array of strings, wordsDict, and two target words, word1 and word2. We must find the minimum distance between any occurrence of these two words in the array.

leetcodemediumarraystring
LeetCode 1310 - XOR Queries of a Subarray

You asked for the complete guide in a single response, but your previous message includes two separate LeetCode problems

leetcodemediumarraybit-manipulationprefix-sum
LeetCode 832 - Flipping an Image

The problem requires transforming an n x n binary matrix in two steps: first flipping it horizontally, then inverting it.

leetcodeeasyarraytwo-pointersbit-manipulationmatrixsimulation
LeetCode 554 - Brick Wall

The problem gives us a wall made of multiple rows of bricks. Each row is represented as an array of integers, where each integer describes the width of a brick. Every brick has height 1, and all rows together form a rectangle with the same total width.

leetcodemediumarrayhash-table
LeetCode 571 - Find Median Given Frequency of Numbers

This problem provides a compressed representation of a dataset instead of listing every number individually. The table Numbers contains two columns: - num, the actual number - frequency, how many times that number appears If we expanded the table into a full sorted array, each…

leetcodeharddatabase
LeetCode 1327 - List the Products Ordered in a Period

The problem asks us to list all products that have been ordered in February 2020 with a total quantity of at least 100 u

leetcodeeasydatabase
LeetCode 1702 - Maximum Binary String After Change

This problem gives us a binary string consisting only of '0' and '1'. We are allowed to repeatedly apply two transformation rules: - Replace "00" with "10" - Replace "10" with "01" We may perform these operations as many times as we want, in any order, and the goal is to…

leetcodemediumstringgreedy
LeetCode 829 - Consecutive Numbers Sum

The problem asks us to determine in how many distinct ways an integer n can be expressed as a sum of consecutive positive integers.

leetcodehardmathenumeration
LeetCode 501 - Find Mode in Binary Search Tree

This problem asks us to find the mode(s) in a Binary Search Tree (BST). A mode is the value that appears most frequently in the tree. Since duplicates are allowed in this BST definition, a value may occur multiple times. The input is the root node of a BST.

leetcodeeasytreedepth-first-searchbinary-search-treebinary-tree
CF 69B - Bets

Each athlete runs through a contiguous interval of sections. While an athlete is inside a section, they spend exactly t[i] time on that section, so the winner of a section is simply the active athlete with the smallest t.

codeforcescompetitive-programminggreedyimplementation
CF 83B - Doctor

We have a queue of animals waiting for the doctor. Animal i must visit the doctor exactly a[i] times before leaving forever. Whenever an animal is examined, one of two things happens. If it still needs more visits, it immediately moves to the back of the queue.

codeforcescompetitive-programmingbinary-searchmathsortings
LeetCode 119 - Pascal's Triangle II

This problem asks us to return a specific row from Pascal's Triangle. The input, rowIndex, represents the zero-based index of the row we want to generate.

leetcodeeasyarraydynamic-programming
LeetCode 80 - Remove Duplicates from Sorted Array II

This problem asks us to modify a sorted integer array in-place so that every unique value appears at most twice. Since the array is already sorted in non-decreasing order, duplicate values will always appear next to each other, which is a very important property that makes an…

leetcodemediumarraytwo-pointers
CF 57A - Square Earth?

We are asked to find the shortest distance between two points lying on the perimeter of a square of side length n. The square is aligned with the axes, so its corners are at (0,0), (n,0), (0,n), and (n,n). The two points are guaranteed to lie on the edges, not in the interior.

codeforcescompetitive-programmingdfs-and-similargreedyimplementation
LeetCode 865 - Smallest Subtree with all the Deepest Nodes

The problem gives us the root of a binary tree and asks us to find the smallest subtree that contains all of the deepest nodes in the tree. The depth of a node is defined as the number of edges between that node and the root. The root itself has depth 0.

leetcodemediumhash-tabletreedepth-first-searchbreadth-first-searchbinary-tree
CF 111D - Petya and Coloring

We have an $n times m$ grid, and every cell must be painted with one of $k$ colors. The restriction is about every vertical cut between columns.

codeforcescompetitive-programmingcombinatoricsdp
LeetCode 1186 - Maximum Subarray Sum with One Deletion

The problem is asking us to find the maximum sum of a contiguous subarray in a given integer array, with the additional twist that we are allowed to delete at most one element from that subarray.

leetcodemediumarraydynamic-programming
LeetCode 1642 - Furthest Building You Can Reach

The problem gives us an array heights, where each value represents the height of a building. You start at building 0 and

leetcodemediumarraygreedyheap-(priority-queue)
LeetCode 118 - Pascal's Triangle

The problem is asking us to generate the first numRows of Pascal's triangle, which is a triangular arrangement of numbers where each number is the sum of the two numbers directly above it.

leetcodeeasyarraydynamic-programming
LeetCode 1715 - Count Apples and Oranges

This problem asks us to compute the total number of apples and oranges across all boxes, taking into account that some boxes may contain a chest. The Boxes table gives us the count of apples and oranges in each box, and optionally the chestid if a chest is present in that box.

leetcodemediumdatabase
LeetCode 1505 - Minimum Possible Integer After at Most K Adjacent Swaps On Digits

The problem gives us a numeric string num and an integer k. Each operation allows us to swap two adjacent digits. We may

leetcodehardstringgreedybinary-indexed-treesegment-tree
LeetCode 399 - Evaluate Division

This problem gives us a collection of equations between variables, where each equation represents a division relationship.

leetcodemediumarraystringdepth-first-searchbreadth-first-searchunion-findgraph-theoryshortest-path
LeetCode 776 - Split BST

The problem asks us to split a binary search tree (BST) into two separate subtrees based on a target value. Specifically, the first subtree should contain all nodes with values less than or equal to the target, and the second subtree should contain all nodes with values…

leetcodemediumtreebinary-search-treerecursionbinary-tree
LeetCode 155 - Min Stack

The problem asks us to design a custom stack data structure that behaves like a normal stack, while also supporting an additional operation called getMin(). This operation must return the minimum value currently stored in the stack, and it must do so in constant time, O(1).

leetcodemediumstackdesign
CF 45J - Planting Trees

We need to place the integers from 1 to n * m into an n × m grid so that every pair of side-adjacent cells differs by at least 2. Two cells are adjacent only if they share an edge, diagonal neighbors do not matter.

codeforcescompetitive-programmingconstructive-algorithms
CF 100C - A+B

The task looks trivial at first glance: read two integers and print their sum. The catch is hidden inside the constraints. Each number can contain up to 500 decimal digits, far larger than the range of standard 32-bit or 64-bit integers in many languages.

codeforcescompetitive-programming*specialimplementation
LeetCode 1699 - Number of Calls Between Two Persons

This problem provides a database table named Calls, where each row represents a phone call between two people. The table contains three columns: | Column | Meaning | | --- | --- | | fromid | The caller | | toid | The receiver | | duration | Duration of the call | The important…

leetcodemediumdatabase
LeetCode 1201 - Ugly Number III

The problem defines an "ugly number" as any positive integer that is divisible by at least one of the three given integers a, b, or c.

leetcodemediummathbinary-searchcombinatoricsnumber-theory
CF 117B - Very Interesting Game

We are asked to simulate a two-player game involving numbers represented as nine-digit strings. The first player selects a string s1 that represents a number not exceeding a given value a. The second player responds with a string s2 representing a number not exceeding b.

codeforcescompetitive-programmingbrute-forcenumber-theory
LeetCode 1549 - The Most Recent Orders for Each Product

This problem asks us to find the most recent order for every product that has been ordered at least once. We are given t

leetcodemediumdatabase
LeetCode 670 - Maximum Swap

The problem asks us to take an integer num and find the maximum number we can create by swapping at most two digits. In other words, we can pick two positions in the number, swap their digits, and we want the resulting number to be as large as possible.

leetcodemediummathgreedy
LeetCode 94 - Binary Tree Inorder Traversal

This problem asks us to perform an inorder traversal on a binary tree and return the values of the visited nodes in the correct order. A binary tree is a hierarchical data structure where each node can have at most two children, a left child and a right child.

leetcodeeasystacktreedepth-first-searchbinary-tree
LeetCode 606 - Construct String from Binary Tree

This problem asks us to convert a binary tree into a string using a very specific preorder traversal format. We must visit nodes in the order root → left subtree → right subtree, and represent the structure of the tree using parentheses.

leetcodemediumstringtreedepth-first-searchbinary-tree
CF 38F - Smart Boy

We start with an empty string. The first player picks any single letter that appears somewhere inside at least one dictionary word. After that, players alternately extend the current string by adding exactly one character either to the front or to the back.

codeforcescompetitive-programmingdpgamesstrings
LeetCode 1482 - Minimum Number of Days to Make m Bouquets

This problem asks us to determine the minimum number of days required to make a given number of bouquets from a garden o

leetcodemediumarraybinary-search
LeetCode 1499 - Max Value of Equation

This guide will focus on the optimal monotonic queue solution, which achieves linear time complexity and is necessary to

leetcodehardarrayqueuesliding-windowheap-(priority-queue)monotonic-queue
LeetCode 811 - Subdomain Visit Count

In this problem, we are given a list of strings where each string represents a visit count paired with a domain name. Each input entry has the form: For example: means the domain discuss.leetcode.com was visited 9001 times.

leetcodemediumarrayhash-tablestringcounting
LeetCode 1845 - Seat Reservation Manager

The problem requires designing a system to manage seat reservations for n seats numbered from 1 to n. You need to implement a SeatManager class with two main operations: reserve and unreserve.

leetcodemediumdesignheap-(priority-queue)
LeetCode 1194 - Tournament Winners

The problem asks us to determine the winner in each group of players based on their accumulated points across multiple matches. We are given two tables: Players and Matches.

leetcodeharddatabase
CF 98B - Help King

We are asked to simulate a fair random selection of one knight out of n using a coin that can only produce two outcomes. Each coin flip has an equal probability of landing heads or tails.

codeforcescompetitive-programmingimplementationprobabilitiestrees
CF 106A - Card Game

We are given the trump suit for a game of Durak and two cards. The task is to decide whether the first card can beat the second card under the game rules. Each card has a rank and a suit. The ranks are ordered as: A card can beat another card in exactly two situations.

codeforcescompetitive-programmingimplementation
LeetCode 1551 - Minimum Operations to Make Array Equal

The problem presents an array arr of length n where each element is defined by the formula arr[i] = 2 i + 1. This genera

leetcodemediummath
CF 39G - Inverse Function

We are given the source code of a tiny recursive function f(n) written in a heavily restricted subset of C++. The function only contains sequential if (...) return ...; statements and unconditional return ...; statements.

codeforcescompetitive-programmingimplementation
LeetCode 432 - All O`one Data Structure

The problem asks us to design a special data structure that stores string keys together with their occurrence counts.

leetcodehardhash-tablelinked-listdesigndoubly-linked-list
CF 126B - Password

We are given a single lowercase string and need to find the longest string that satisfies three conditions at the same time. The chosen string must be a prefix of the original string, a suffix of the original string, and also appear somewhere strictly inside the string.

codeforcescompetitive-programmingbinary-searchdphashingstring-suffix-structuresstrings
LeetCode 295 - Find Median from Data Stream

The problem asks us to design a data structure that continuously receives integers from a stream and can efficiently return the median of all numbers seen so far. The median is defined as the middle element in a sorted list.

leetcodehardtwo-pointersdesignsortingheap-(priority-queue)data-stream
CF 120J - Minimum Sum

We are given a set of points in two-dimensional space, where each point can be thought of as a vector from the origin. Each vector has two coordinates, x and y, and we are allowed to independently flip the sign of each coordinate.

codeforcescompetitive-programmingdivide-and-conquergeometrysortings
LeetCode 259 - 3Sum Smaller

The problem asks us to count how many distinct index triplets (i, j, k) satisfy two conditions: 1. The indices are ordered such that 0 <= i < j < k < n 2.

leetcodemediumarraytwo-pointersbinary-searchsorting
LeetCode 1541 - Minimum Insertions to Balance a Parentheses String

This problem asks us to transform a string of parentheses into a special kind of balanced parentheses string using the m

leetcodemediumstringstackgreedy
CF 39C - Moon Craters

Each crater is described by a center coordinate c and a radius r. Since the robot moves along a line, every crater can be represented on that line by its interval: $[c-r, c+r]$ Professor Okulov’s rule says that any two selected craters must either be completely disjoint or…

codeforcescompetitive-programmingdpsortings
CF 100H - Battleship

We are given several 10 × 10 Battleship boards. Each cell is either empty or occupied by part of a ship. The task is to verify whether every occupied cell belongs to a valid fleet configuration.

codeforcescompetitive-programming*specialdfs-and-similarimplementation
LeetCode 1036 - Escape a Large Maze

The problem gives us a massive 1,000,000 x 1,000,000 grid. Each cell is identified by coordinates (x, y), and movement is allowed in four directions: up, down, left, and right. Some cells are blocked, meaning we cannot step onto them.

leetcodehardarrayhash-tabledepth-first-searchbreadth-first-search
LeetCode 1406 - Stone Game III

In this game, two players, Alice and Bob, take turns removing stones from the beginning of a row. Each stone has an inte

leetcodehardarraymathdynamic-programminggame-theory
LeetCode 553 - Optimal Division

The problem gives us an array of positive integers, and the array elements are combined using division operations in order from left to right. For example, if the input is: the default expression becomes: which evaluates as: because division is left associative.

leetcodemediumarraymathdynamic-programming
CF 107A - Dorm Water Supply

The houses and pipes form a directed graph with a very special structure. Every house can have at most one incoming pipe and at most one outgoing pipe. That restriction changes the graph from a general directed graph into a collection of independent chains.

codeforcescompetitive-programmingdfs-and-similargraphs
LeetCode 956 - Tallest Billboard

This problem asks us to split a collection of steel rods into two groups such that both groups have exactly the same total height. Among all possible equal-height pairs, we want the maximum achievable height. Each rod can be used in one of three ways: 1.

leetcodehardarraydynamic-programming
LeetCode 1542 - Find Longest Awesome Substring

The problem asks us to find the length of the longest awesome substring in a given string s consisting of digits. A subs

leetcodehardhash-tablestringbit-manipulation
LeetCode 100 - Same Tree

The problem asks us to determine whether two binary trees are exactly the same. We are given the roots of two binary trees, p and q. A binary tree consists of nodes where each node contains a value and references to a left child and a right child.

leetcodeeasytreedepth-first-searchbreadth-first-searchbinary-tree
LeetCode 1370 - Increasing Decreasing String

The problem requires us to reorder a string s by repeatedly picking characters in a specific increasing and decreasing p

leetcodeeasyhash-tablestringcounting
LeetCode 1210 - Minimum Moves to Reach Target with Rotations

This problem models a shortest path search on a grid, but the moving object is not a single cell. Instead, the object is a snake that occupies exactly two adjacent cells.

leetcodehardarraybreadth-first-searchmatrix
CF 75B - Facetook Priority Wall

We are given the name of a user on a social network and a sequence of activity messages between users. Every activity contributes a certain number of points between the two people involved.

codeforcescompetitive-programmingexpression-parsingimplementationstrings
CF 25B - Phone numbers

We are given a string of digits representing a phone number. The task is to split this string into pieces where every piece has length either 2 or 3. The groups must appear in the original order, and they are joined with - characters in the output.

codeforcescompetitive-programmingimplementation
LeetCode 440 - K-th Smallest in Lexicographical Order

The problem asks us to find the k-th smallest number in lexicographical order among all integers from 1 to n. Lexicographical order means dictionary order, not numerical order.

leetcodehardtrie