brain

tamnd's digital brain — notes, problems, research

42648 notes

LeetCode 1408 - String Matching in an Array

You included two different problems in one message, and the second problem (LeetCode 1408) appears to replace the first

leetcodeeasyarraystringstring-matching
LeetCode 395 - Longest Substring with At Least K Repeating Characters

The problem asks us to find the length of the longest substring in which every character appears at least k times. A substring is a contiguous sequence of characters inside the original string.

leetcodemediumhash-tablestringdivide-and-conquersliding-window
LeetCode 446 - Arithmetic Slices II - Subsequence

The problem asks us to count how many arithmetic subsequences exist inside a given integer array nums. An arithmetic sequence is a sequence where the difference between consecutive elements is constant. The sequence must contain at least three elements.

leetcodehardarraydynamic-programming
CF 10C - Digital Root

We are given an integer N. Consider all triples (A, B, C) where every value lies in the range [1, N].

codeforcescompetitive-programmingnumber-theory
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
CF 22A - Second Order Statistics

We are given a small array of integers and need to find the smallest value that is strictly larger than the minimum element in the array.

codeforcescompetitive-programmingbrute-force
LeetCode 572 - Subtree of Another Tree

This problem asks us to determine whether one binary tree appears as an exact subtree inside another binary tree.

leetcodeeasytreedepth-first-searchstring-matchingbinary-treehash-function
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 1318 - Minimum Flips to Make a OR b Equal to c

The problem gives us three positive integers, a, b, and c. We are allowed to flip individual bits in either a or b. A flip means changing a bit from 0 to 1 or from 1 to 0. Our goal is to perform the minimum number of bit flips so that: The OR operation works bit by bit.

leetcodemediumbit-manipulation
LeetCode 721 - Accounts Merge

This problem asks us to merge user accounts based on shared email addresses. Each account is represented as a list of strings. The first string is the user's name, and every remaining string is an email address associated with that account.

leetcodemediumarrayhash-tablestringdepth-first-searchbreadth-first-searchunion-findsorting
CF 9C - Hexadecimal's Numbers

We are asked to count how many numbers from 1 to n consist only of the digits 0 and 1 in their decimal representation. In other words, Hexadecimal's memory only stores numbers that, when written in base 10, contain no digits other than 0 or 1.

codeforcescompetitive-programmingbrute-forceimplementationmath
LeetCode 284 - Peeking Iterator

The problem asks us to extend the functionality of a standard iterator with an additional peek operation. A standard iterator provides two operations: next(), which returns the next element in the sequence and advances the pointer, and hasNext(), which tells whether there are…

leetcodemediumarraydesigniterator
LeetCode 1568 - Minimum Number of Days to Disconnect Island

The problem gives us a binary matrix where each cell is either land (1) or water (0). Land cells that touch vertically or horizontally belong to the same island. A grid is considered connected only when there is exactly one island in the entire grid.

leetcodehardarraydepth-first-searchbreadth-first-searchmatrixstrongly-connected-component
LeetCode 362 - Design Hit Counter

The problem asks us to design a data structure that tracks how many events, called "hits", occurred during the last 5 minutes. Every hit comes with a timestamp measured in seconds, and timestamps are guaranteed to arrive in chronological order.

leetcodemediumarraybinary-searchdesignqueuedata-stream
LeetCode 779 - K-th Symbol in Grammar

The problem defines a special binary grammar sequence that grows row by row. The first row contains only a single value: Every later row is generated from the previous one using these rules: - Replace every 0 with 01 - Replace every 1 with 10 This means the rows evolve like…

leetcodemediummathbit-manipulationrecursion
CF 135C - Zero-One

We are given a string consisting of 0, 1, and ?. Each character represents a card in a row. During the game, players alternately remove one card until only two cards remain.

codeforcescompetitive-programmingconstructive-algorithmsgamesgreedy
LeetCode 77 - Combinations

This problem asks us to generate all possible combinations of size k from the numbers in the inclusive range [1, n].

leetcodemediumbacktracking
LeetCode 90 - Subsets II

The problem asks us to generate every possible subset of a given integer array. A subset is any selection of elements from the array, including the empty subset and the subset containing all elements.

leetcodemediumarraybacktrackingbit-manipulation
LeetCode 1304 - Find N Unique Integers Sum up to Zero

The problem asks us to construct an array containing exactly n unique integers whose total sum is equal to 0. The keywor

leetcodeeasyarraymath
LeetCode 428 - Serialize and Deserialize N-ary Tree

LeetCode 428, LeetCode Serialize and Deserialize N-ary Tree, asks us to design a reversible encoding system for an N-ary tree. The problem is not asking for a specific serialization format.

leetcodehardstringtreedepth-first-searchbreadth-first-search
LeetCode 1906 - Minimum Absolute Difference Queries

The problem asks us to compute the minimum absolute difference in subarrays of a given integer array nums for multiple q

leetcodemediumarrayprefix-sum
LeetCode 276 - Paint Fence

The problem gives us a fence with n posts and k available colors. Every fence post must be painted using exactly one of those colors. The important restriction is that we are not allowed to have three or more consecutive posts painted with the same color.

leetcodemediumdynamic-programming
LeetCode 1339 - Maximum Product of Splitted Binary Tree

That is a long, structured technical document with multiple required sections, complete Python and Go implementations, w

leetcodemediumtreedepth-first-searchbinary-tree
LeetCode 465 - Optimal Account Balancing

The problem gives a list of money transfers between people. Each transaction is represented as [from, to, amount], meaning one person paid a certain amount to another person.

leetcodehardarraydynamic-programmingbacktrackingbit-manipulationbitmask
CF 20C - Dijkstra?

We are given an undirected weighted graph. Every edge connects two vertices and has a positive cost. The task is to start at vertex 1, reach vertex n, and print one shortest path. If no route exists, we print -1.

codeforcescompetitive-programminggraphsshortest-paths
LeetCode 566 - Reshape the Matrix

The problem is asking us to take an existing m x n matrix and "reshape" it into a new matrix with r rows and c columns. Reshaping means rearranging the elements in the matrix in row-major order (left-to-right, top-to-bottom) without changing the order of the elements themselves.

leetcodeeasyarraymatrixsimulation
LeetCode 887 - Super Egg Drop

The problem asks us to determine the minimum number of moves required to identify a critical floor in a building using a limited number of eggs.

leetcodehardmathbinary-searchdynamic-programming
LeetCode 985 - Sum of Even Numbers After Queries

The problem gives us an integer array nums and a list of update operations called queries. Each query contains two values: - vali, the amount to add - indexi, the position in the array to update For every query, we must first update the array element: After applying the update…

leetcodemediumarraysimulation
CF 60D - Savior

Each lawn contains a distinct positive integer. Two lawns are considered connected if their numbers can appear together in some primitive Pythagorean triple.

codeforcescompetitive-programmingbrute-forcedsumath
LeetCode 1136 - Parallel Courses

The problem is asking us to determine the minimum number of semesters required to complete n courses given a set of prerequisite relationships.

leetcodemediumgraph-theorytopological-sort
LeetCode 1355 - Activity Participants

This problem asks us to analyze participation counts for different activities and return only the activities whose parti

leetcodemediumdatabase
LeetCode 299 - Bulls and Cows

The problem gives two strings, secret and guess, representing two numbers of equal length. We need to compare them and return a hint in the format "xAyB". A "bull" is a digit that matches in both value and position.

leetcodemediumhash-tablestringcounting
CF 31E - TV Game

We are given a string of 2n digits. The digits are processed strictly from left to right. At every step, either Homer or Marge takes the current leftmost digit and appends it to their own number. By the end, both players must have taken exactly n digits.

codeforcescompetitive-programmingdp
CF 87B - Vasya and Types

The language in this problem has only two real base types, void and errtype. Every other type is defined through typedef, and every query asks us to evaluate a type expression with typeof. A type expression is built from a base name plus some number of and & operators.

codeforcescompetitive-programmingimplementationstrings
CF 65D - Harry Potter and the Sorting Hat

We process students one by one. Each student either has a fixed house, represented by one of the letters G, H, R, S, or has ambiguous ancestry, represented by ?. A fixed student always goes into that house. A ? student behaves differently.

codeforcescompetitive-programmingbrute-forcedfs-and-similarhashing
LeetCode 1090 - Largest Values From Labels

The problem gives us two arrays, values and labels, where each index represents a single item. The item at index i has a value values[i] and a category or group identifier labels[i].

leetcodemediumarrayhash-tablegreedysortingcounting
LeetCode 1453 - Maximum Number of Darts Inside of a Circular Dartboard

In this problem, we are given the coordinates of several darts thrown onto a 2D plane. Each dart is represented as a poi

leetcodehardarraymathgeometry
CF 24E - Berland collider

We are given a one-dimensional collider with n particles, each with a starting position x_i and a velocity v_i. Positive velocity means a particle moves right, negative velocity means it moves left.

codeforcescompetitive-programmingbinary-search
CF 131F - Present to Mom

We are given a black-and-white photo represented as a grid of size n × m where each cell is either '1' for a white pixel or '0' for a black pixel.

codeforcescompetitive-programmingbinary-searchtwo-pointers
LeetCode 924 - Minimize Malware Spread

In this problem, we are given an undirected graph represented as an adjacency matrix. Each node represents a computer in a network, and an edge between two nodes means those computers are directly connected. Some subset of nodes is initially infected with malware.

leetcodehardarrayhash-tabledepth-first-searchbreadth-first-searchunion-findgraph-theory
CF 71B - Progress Bar

We are asked to construct a graphical progress bar as an array of squares, where each square has a saturation value. The bar has a total of n squares, and the maximum saturation is k.

codeforcescompetitive-programmingimplementationmath
CF 100J - Interval Coloring

We are asked to color a collection of intervals on the number line such that no three intervals with the same color form a "triple overlap pattern.

codeforcescompetitive-programming*specialgreedymath
LeetCode 1228 - Missing Number In Arithmetic Progression

The problem asks us to find a missing value from an array that originally formed an arithmetic progression (AP). An arithmetic progression is a sequence where the difference between consecutive terms is constant, i.e., arr[i + 1] - arr[i] is the same for every consecutive pair.

leetcodeeasyarraymath
LeetCode 1206 - Design Skiplist

This problem asks us to implement a Skiplist from scratch, a probabilistic data structure that allows efficient search, insertion, and deletion operations.

leetcodehardlinked-listdesign
LeetCode 1362 - Closest Divisors

The problem gives us an integer num, and asks us to find two integers whose product equals either num + 1 or num + 2, su

leetcodemediummath
LeetCode 1590 - Make Sum Divisible by P

This problem asks us to determine the smallest contiguous subarray we can remove from a given array of positive integers

leetcodemediumarrayhash-tableprefix-sum
LeetCode 1099 - Two Sum Less Than K

This problem asks us to find the maximum sum of any two distinct numbers in an integer array nums such that their sum is strictly less than a given integer k.

leetcodeeasyarraytwo-pointersbinary-searchsorting
CF 16D - Logging

We are given a sequence of log entries in the exact order they were written. Originally every entry had both a date and a time, but the dates were lost, so only the 12-hour clock timestamps remain.

codeforcescompetitive-programmingimplementationstrings
LeetCode 1027 - Longest Arithmetic Subsequence

Your requested guide is very long and detailed, especially with all required sections, full prose explanations, worked traces, Python and Go implementations, complexity proofs, and extensive test coverage.

leetcodemediumarrayhash-tablebinary-searchdynamic-programming
LeetCode 338 - Counting Bits

The problem asks us to compute the number of set bits, also called population count or popcount, for every integer from 0 through n. A set bit is a bit with value 1 in the binary representation of a number.

leetcodeeasydynamic-programmingbit-manipulation
LeetCode 591 - Tag Validator

This problem asks us to validate whether a given string represents a correctly structured code snippet according to a custom XML-like syntax. At first glance, it resembles parsing HTML or XML tags, but the validation rules are stricter and more specialized.

leetcodehardstringstack
CF 93B - End of Exams

We are asked to distribute milk from a set of bottles into cups such that each bottle contributes to at most two cups, and all cups end up with the same total volume. Specifically, we have n bottles, each containing w units of milk, and m friends who each receive one cup.

codeforcescompetitive-programminggreedy
CF 96A - Football

We are given a string made only of '0' and '1'. Each character represents the team of a football player standing in a line. A dangerous situation happens if at least seven consecutive players belong to the same team.

codeforcescompetitive-programmingimplementationstrings
LeetCode 1427 - Perform String Shifts

This problem asks us to simulate a sequence of string shift operations on a given string s. Each operation in the shift

leetcodeeasyarraymathstring
CF 37C - Old Berland Language

We need to construct a binary prefix code.

codeforcescompetitive-programmingdata-structuresgreedytrees
CF 89E - Fire and Ice

Solomon stands on the fortress wall at position 0. To his right there may exist a chain of ice blocks occupying positions 1, 2, .... Initially there are no blocks at all. The battlefield is a line of length n. At battlefield position i, there may be a demon with strength a[i].

codeforcescompetitive-programminggreedy
LeetCode 1789 - Primary Department for Each Employee

The problem provides a database table named Employee that stores information about which departments employees belong to.

leetcodeeasydatabase
LeetCode 1800 - Maximum Ascending Subarray Sum

The problem gives an array of positive integers called nums. We must find the contiguous subarray that is strictly increasing and has the largest possible sum. A subarray is contiguous, which means the elements must appear next to each other in the original array.

leetcodeeasyarray
LeetCode 288 - Unique Word Abbreviation

The problem asks us to design a data structure that determines whether a word's abbreviation is unique within a given dictionary.

leetcodemediumarrayhash-tablestringdesign
LeetCode 183 - Customers Who Never Order

This problem is asking us to identify all customers from a Customers table who have never placed an order according to the Orders table. In other words, we are looking for entries in Customers that do not have a corresponding customerId in the Orders table.

leetcodeeasydatabase
LeetCode 1033 - Moving Stones Until Consecutive

The problem presents three stones placed on distinct positions along a one-dimensional X-axis, represented by integers a, b, and c.

leetcodemediummathbrainteaser
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
CF 74E - Shift It!

We have a 6 × 6 board containing the characters 0-9 and A-Z, each appearing exactly once. The target configuration is fixed: characters must appear in row-major order. The only allowed moves are cyclic shifts of complete rows or complete columns.

codeforcescompetitive-programmingconstructive-algorithms
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
CF 82C - General Mobilization

We have a rooted tree with root at city 1. Every city initially contains exactly one military division. Division i starts in city i and has priority a[i], where a smaller value means higher priority. Each edge has a capacity.

codeforcescompetitive-programmingdata-structuresdfs-and-similarsortings
CF 120D - Three Sons

We have a rectangular cornfield represented as a grid of size n × m, where each cell contains a certain number of tons of corn. The father wants to divide this field among three sons in such a way that each son receives exactly a predetermined amount of corn: A, B, or C tons.

codeforcescompetitive-programmingbrute-force
LeetCode 1371 - Find the Longest Substring Containing Vowels in Even Counts

This problem asks us to find the length of the longest contiguous substring in which every vowel appears an even number

leetcodemediumhash-tablestringbit-manipulationprefix-sum
LeetCode 1008 - Construct Binary Search Tree from Preorder Traversal

Let's dive deep and construct a thorough technical guide for LeetCode 1008, following your formatting rules. The problem asks us to construct a binary search tree (BST) from a given preorder traversal array.

leetcodemediumarraystacktreebinary-search-treemonotonic-stackbinary-tree
LeetCode 1760 - Minimum Limit of Balls in a Bag

You are given several bags of balls, where nums[i] represents how many balls are inside the i-th bag. You are allowed to perform at most maxOperations split operations.

leetcodemediumarraybinary-search
CF 75E - Ship's Shortest Path

We are given two points in the plane, the ship's starting position and destination, together with a convex polygon representing an island. Moving through the sea costs 1 per unit distance. Moving through the interior of the island costs 2 per unit distance.

codeforcescompetitive-programminggeometryshortest-paths
LeetCode 983 - Minimum Cost For Tickets

In this problem, we are given a list of travel days during a single year and the costs of three different train passes. Each pass covers a consecutive range of days: - A 1-day pass covers exactly one day. - A 7-day pass covers seven consecutive days.

leetcodemediumarraydynamic-programming
LeetCode 637 - Average of Levels in Binary Tree

In this problem, we are given the root node of a binary tree, and we need to compute the average value of all nodes at each depth level of the tree. A binary tree is organized into levels.

leetcodeeasytreedepth-first-searchbreadth-first-searchbinary-tree
LeetCode 303 - Range Sum Query - Immutable

The problem asks us to design a data structure that supports efficient range sum queries on a fixed array. We are given an integer array nums, and after initialization, the array never changes.

leetcodeeasyarraydesignprefix-sum
LeetCode 1251 - Average Selling Price

This problem asks us to compute the average selling price for every product based on two tables: Prices and UnitsSold. T

leetcodeeasydatabase
LeetCode 171 - Excel Sheet Column Number

This problem asks us to convert an Excel-style column title into its corresponding numerical index. In Excel spreadsheets, columns are labeled alphabetically: The labeling system works similarly to a positional number system, except instead of digits 0-9, it uses letters A-Z…

leetcodeeasymathstring
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
CF 128A - Statues

We have an 8 × 8 board. Maria starts in the bottom-left corner, Anna stays permanently in the top-right corner, and several statues occupy other cells. The game proceeds in rounds. Maria moves first, then every statue moves one row downward simultaneously.

codeforcescompetitive-programmingdfs-and-similar
LeetCode 1750 - Minimum Length of String After Deleting Similar Ends

The problem gives us a string s containing only the characters 'a', 'b', and 'c'. We may repeatedly perform a deletion operation on the string.

leetcodemediumtwo-pointersstring
CF 124B - Permutations

We are given several strings of digits, all with the same length. We may choose one permutation of digit positions and apply it to every string. After rearranging the digits according to that shared permutation, each string becomes a new integer, possibly with leading zeroes.

codeforcescompetitive-programmingbrute-forcecombinatoricsimplementation
LeetCode 1785 - Minimum Elements to Add to Form a Given Sum

The problem gives us an integer array nums, a maximum allowed absolute value limit, and a target sum called goal.

leetcodemediumarraygreedy
LeetCode 264 - Ugly Number II

The problem asks us to generate the sequence of ugly numbers and return the nth value in that sequence. An ugly number is defined as a positive integer whose only prime factors are 2, 3, and 5.

leetcodemediumhash-tablemathdynamic-programmingheap-(priority-queue)
LeetCode 547 - Number of Provinces

The problem is asking us to determine the number of provinces in a network of cities. Each city can be connected directly to other cities, and indirectly through chains of connections.

leetcodemediumdepth-first-searchbreadth-first-searchunion-findgraph-theory
CF 73E - Morrowindows

Each viewing mode groups the inventory into pages of size ai. If the inventory contains k items, then the game shows $bi = leftlceil frac{k}{ai} rightrceil$ pages in that mode. Vasya does not know the actual value of k, only that 2 ≤ k ≤ x.

codeforcescompetitive-programmingmathnumber-theory
LeetCode 1289 - Minimum Falling Path Sum II

The problem asks us to compute the minimum sum of a falling path with non-zero shifts in a square n x n matrix. A fallin

leetcodehardarraydynamic-programmingmatrix
LeetCode 1254 - Number of Closed Islands

This problem provides a 2D grid representing a map of land and water. Cells with 0 represent land, and cells with 1 repr

leetcodemediumarraydepth-first-searchbreadth-first-searchunion-findmatrix
CF 28A - Bender Problem

We are given a sequence of nails in the plane, each with integer coordinates, and a collection of straight rods. The nails define the vertices of a closed polyline that only moves along horizontal or vertical segments.

codeforcescompetitive-programmingimplementation
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 650 - 2 Keys Keyboard

The problem is asking for the minimum number of operations required to generate exactly n characters 'A' on a notepad starting with a single 'A'.

leetcodemediummathdynamic-programming
LeetCode 343 - Integer Break

The problem asks us to split a positive integer n into the sum of at least two positive integers, then maximize the product of those integers. In other words, we are not allowed to keep the number as-is.

leetcodemediummathdynamic-programming
LeetCode 1015 - Smallest Integer Divisible by K

The problem asks us to find the length of the smallest positive integer that satisfies two conditions: 1. The integer contains only the digit 1 2. The integer is divisible by k Such numbers are commonly called repunits.

leetcodemediumhash-tablemath
LeetCode 1818 - Minimum Absolute Sum Difference

The problem gives two arrays of positive integers, nums1 and nums2, both of equal length n. The goal is to calculate the absolute sum difference between these arrays, which is the sum of the absolute differences at each index: |nums1[i] - nums2[i]|.

leetcodemediumarraybinary-searchsortingordered-set
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 2143 - Choose Numbers From Two Arrays in Range

In this problem, we are given two arrays, nums1 and nums2, both of length n. For every index i, we must choose exactly o

leetcodehardarraydynamic-programming
LeetCode 1447 - Simplified Fractions

The problem asks us to generate all simplified fractions between 0 and 1 (exclusive) where the denominator does not exce

leetcodemediummathstringnumber-theory
LeetCode 82 - Remove Duplicates from Sorted List II

This problem asks us to process a sorted singly linked list and remove every value that appears more than once. The important distinction is that we are not keeping one copy of duplicated values. Instead, every node containing a duplicated value must be removed entirely.

leetcodemediumlinked-listtwo-pointers
LeetCode 1365 - How Many Numbers Are Smaller Than the Current Number

The problem asks us to determine, for each element in an array, how many elements in the same array are strictly smaller than it. In other words, for an element nums[i], we count all elements nums[j] such that nums[j] < nums[i] and j != i.

leetcodeeasyarrayhash-tablesortingcounting-sort
LeetCode 1200 - Minimum Absolute Difference

The problem asks us to find all pairs of numbers in an array that have the smallest absolute difference. In other words, given a list of distinct integers, we want to identify every pair [a, b] such that the difference b - a is minimized across all possible pairs in the array…

leetcodeeasyarraysorting
LeetCode 1565 - Unique Orders and Customers Per Month

This problem requires analyzing a table of orders to calculate monthly statistics. Specifically, for each unique month present in the Orders table, we need to determine two metrics: the number of unique orders and the number of unique customers whose orders have an invoice…

leetcodeeasydatabase
LeetCode 279 - Perfect Squares

The problem asks for the minimum number of perfect square numbers whose sum equals a given integer n. A perfect square is a number that can be written as x x for some integer x. Examples include 1, 4, 9, 16, and 25.

leetcodemediummathdynamic-programmingbreadth-first-search
LeetCode 1649 - Create Sorted Array through Instructions

The problem asks us to simulate building a sorted array incrementally. We process the instructions array from left to ri

leetcodehardarraybinary-searchdivide-and-conquerbinary-indexed-treesegment-treemerge-sortordered-set