brain

tamnd's digital brain — notes, problems, research

42641 notes

LeetCode 696 - Count Binary Substrings

The problem gives us a binary string, meaning the string contains only the characters '0' and '1'. We need to count how many substrings satisfy two conditions simultaneously: 1. The substring contains the same number of 0s and 1s. 2.

leetcodeeasytwo-pointersstring
LeetCode 1199 - Minimum Time to Build Blocks

The problem requires determining the minimum amount of time to build all blocks using workers that can either build blocks or split into more workers. You are given a list blocks where blocks[i] indicates the time it takes for a worker to complete the i-th block.

leetcodehardarraymathgreedyheap-(priority-queue)
LeetCode 1883 - Minimum Skips to Arrive at Meeting On Time

You are given a sequence of roads that must be traveled in order. Each road has a distance, and you travel at a fixed sp

leetcodehardarraydynamic-programming
CF 23B - Party

We can think of the party as an undirected friendship graph. Every person is a vertex, and an edge means two people are friends.

codeforcescompetitive-programmingconstructive-algorithmsgraphsmath
LeetCode 972 - Equal Rational Numbers

The problem asks us to determine whether two strings s and t, each representing a rational number in decimal notation, correspond to the same numerical value. These numbers can be expressed as integers, finite decimals, or decimals with repeating parts denoted by parentheses.

leetcodehardmathstring
LeetCode 461 - Hamming Distance

The problem asks us to compute the Hamming distance between two integers. The Hamming distance is defined as the number of bit positions where the two numbers differ in their binary representation. For example, consider x = 1 and y = 4.

leetcodeeasybit-manipulation
LeetCode 1217 - Minimum Cost to Move Chips to The Same Position

The problem asks us to move n chips located at various positions along a one-dimensional line so that they all end up at the same position. Each chip can be moved either by 2 units at zero cost or by 1 unit at a cost of 1.

leetcodeeasyarraymathgreedy
LeetCode 1395 - Count Number of Teams

The problem asks us to count the number of valid teams of three soldiers from a line of n soldiers, where each soldier h

leetcodemediumarraydynamic-programmingbinary-indexed-treesegment-tree
LeetCode 1113 - Reported Posts

The problem is asking us to determine the number of posts that were reported yesterday grouped by the reason for the report.

leetcodeeasydatabase
LeetCode 1537 - Get the Maximum Score

Here’s a complete, detailed technical solution guide for LeetCode 1537 - Get the Maximum Score following your requested

leetcodehardarraytwo-pointersdynamic-programminggreedy
CF 26B - Regular Bracket Sequence

We are given a string consisting solely of opening and closing parentheses. The task is to determine the maximum length of a subsequence that forms a valid, or regular, bracket sequence.

codeforcescompetitive-programminggreedy
LeetCode 1061 - Lexicographically Smallest Equivalent String

Here is the complete, detailed technical solution guide for LeetCode 1061 following your exact formatting requirements.

leetcodemediumstringunion-find
CF 31A - Worms Evolution

We are given an array of worm lengths. Each position represents a different worm form, and we need to find three distinct indices such that the length at one index equals the sum of the lengths at the other two indices.

codeforcescompetitive-programmingimplementation
LeetCode 1698 - Number of Distinct Substrings in a String

The problem asks for the total number of distinct substrings of a given string s. A substring is any contiguous sequence of characters from the string, including single-character substrings and the string itself.

leetcodemediumstringtrierolling-hashsuffix-arrayhash-function
LeetCode 1177 - Can Make Palindrome from Substring

The problem asks us to determine whether certain substrings of a given string s can be rearranged and partially modified to form a palindrome. A palindrome is a string that reads the same forward and backward.

leetcodemediumarrayhash-tablestringbit-manipulationprefix-sum
LeetCode 1633 - Percentage of Users Attended a Contest

This problem asks us to calculate the percentage of users who attended each contest. We are given two tables: Users and

leetcodeeasydatabase
LeetCode 1198 - Find Smallest Common Element in All Rows

The problem asks us to find the smallest element that appears in every row of a given m x n matrix mat, where each row is sorted in strictly increasing order. In other words, we need an element that is common to all rows and is the minimum among all such elements.

leetcodemediumarrayhash-tablebinary-searchmatrixcounting
CF 43E - Race

We are asked to analyze a straight-line race of length _s_ kilometers involving _n_ cars. Each car has a list of driving segments, and each segment specifies a constant speed and a duration. The car moves at that speed for the given time before switching to the next segment.

codeforcescompetitive-programmingbrute-forceimplementationtwo-pointers
LeetCode 494 - Target Sum

The problem asks us to count how many different ways we can assign either a '+' or '-' sign to every number in the array nums such that the resulting arithmetic expression evaluates to target.

leetcodemediumarraydynamic-programmingbacktracking
LeetCode 635 - Design Log Storage System

The problem is asking us to design a log storage system that supports two primary operations: storing logs with unique IDs and timestamps, and retrieving logs based on a timestamp range and granularity.

leetcodemediumhash-tablestringdesignordered-set
LeetCode 113 - Path Sum II

This problem asks us to find all root-to-leaf paths in a binary tree where the sum of the node values equals a given targetSum. A binary tree is provided through the root node, and every node contains an integer value. We are also given an integer targetSum.

leetcodemediumbacktrackingtreedepth-first-searchbinary-tree
LeetCode 382 - Linked List Random Node

The problem gives us the head of a singly linked list and asks us to return a random node value such that every node in the list has exactly the same probability of being selected. The class has two operations: 1. Solution(head) initializes the object with the linked list. 2.

leetcodemediumlinked-listmathreservoir-samplingrandomized
CF 41E - 3-cycles

We need to build an undirected graph on n cities such that no triangle exists. A triangle means three distinct cities where every pair is directly connected.

codeforcescompetitive-programmingconstructive-algorithmsgraphsgreedy
LeetCode 1659 - Maximize Grid Happiness

This problem asks us to place introverts and extroverts inside an m x n grid in a way that maximizes the total happiness score. Every grid cell can either remain empty, contain one introvert, or contain one extrovert.

leetcodeharddynamic-programmingbit-manipulationmemoizationbitmask
LeetCode 491 - Non-decreasing Subsequences

The problem gives us an integer array nums and asks us to return every distinct subsequence that is non-decreasing and has length at least two. A subsequence is formed by deleting zero or more elements from the array without changing the relative order of the remaining elements.

leetcodemediumarrayhash-tablebacktrackingbit-manipulation
LeetCode 723 - Candy Crush

This problem is essentially a simulation of the Candy Crush game, where we need to repeatedly crush candies in a grid until the board reaches a stable state. The input is an m x n matrix of integers representing different types of candies, and 0 represents empty cells.

leetcodemediumarraytwo-pointersmatrixsimulation
CF 132B - Piet

We are asked to simulate a simplified Piet interpreter on a small rectangular grid. Each cell is a pixel with a color between 0 and 9, where 0 is black and other digits are colored blocks.

codeforcescompetitive-programmingimplementation
CF 81E - Pairs

Each student points to exactly one other student, the person they consider their best friend. We may create a pair (a, b) only if either a chose b or b chose a. Every student can belong to at most one pair.

codeforcescompetitive-programmingdfs-and-similardpdsugraphsimplementationtrees
CF 135B - Rectangle and Square

We are given eight distinct points on the plane. The task is to split them into two disjoint groups of four points each. One group must form a square. The other group must form a rectangle.

codeforcescompetitive-programmingbrute-forcegeometrymath
LeetCode 371 - Sum of Two Integers

The problem asks us to compute the sum of two integers without using the arithmetic operators + and -. Instead of relying on normal arithmetic, we must use bit manipulation to simulate how addition works at the binary level. The input consists of two integers, a and b.

leetcodemediummathbit-manipulation
LeetCode 1116 - Print Zero Even Odd

The problem requires us to implement a multithreaded class ZeroEvenOdd that coordinates three separate threads to print numbers in a specific sequence. Thread A prints 0s, Thread B prints even numbers, and Thread C prints odd numbers.

leetcodemediumconcurrency
LeetCode 581 - Shortest Unsorted Continuous Subarray

The problem gives an integer array nums and asks for the length of the shortest continuous subarray such that, if only that subarray is sorted in non-decreasing order, the entire array becomes sorted.

leetcodemediumarraytwo-pointersstackgreedysortingmonotonic-stack
LeetCode 1725 - Number Of Rectangles That Can Form The Largest Square

The problem gives us a list of rectangles, where each rectangle is represented as [li, wi]. Here, li is the rectangle's length and wi is its width. From each rectangle, we want to determine the largest square that can be cut from it.

leetcodeeasyarray
LeetCode 1661 - Average Time of Process per Machine

The problem provides a database table named Activity, which stores information about processes executed on different machines.

leetcodeeasydatabase
LeetCode 470 - Implement Rand10() Using Rand7()

The problem provides access to a single API, rand7(), which returns a uniformly random integer from 1 to 7. The task is to implement another function, rand10(), which must return a uniformly random integer from 1 to 10.

leetcodemediummathrejection-samplingrandomizedprobability-and-statistics
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 1722 - Minimize Hamming Distance After Swap Operations

The problem asks us to find the minimum Hamming distance between two arrays, source and target, after performing any number of swaps on source at positions allowed by allowedSwaps. The Hamming distance is defined as the number of indices i for which source[i] != target[i].

leetcodemediumarraydepth-first-searchunion-find
LeetCode 1819 - Number of Different Subsequences GCDs

The problem asks us to compute how many distinct values can appear as the GCD of some non-empty subsequence of the given array. A subsequence is formed by deleting zero or more elements while preserving order.

leetcodehardarraymathcountingnumber-theory
LeetCode 312 - Burst Balloons

The problem gives us an array nums, where each element represents a balloon containing a number. When we burst a balloon at index i, we gain coins equal to: The important detail is that the neighbors of a balloon change dynamically as balloons are removed.

leetcodehardarraydynamic-programming
LeetCode 425 - Word Squares

The problem is asking us to generate all possible word squares from a given list of unique words. A word square is a square arrangement of words such that the word at row i is identical to the word at column i for every i.

leetcodehardarraystringbacktrackingtrie
CF 27A - Next Test

We are given the indices of tests that already exist in the system. Every index is a positive integer, and all indices are distinct. The task is to find the smallest positive integer that does not appear in the list.

codeforcescompetitive-programmingimplementationsortings
LeetCode 1472 - Design Browser History

The problem is asking us to simulate a single-tab browser with a history mechanism. You start on a homepage, and from there, you can visit new URLs, backtrack a certain number of steps, or forward a certain number of steps.

leetcodemediumarraylinked-liststackdesigndoubly-linked-listdata-stream
LeetCode 1586 - Binary Search Tree Iterator II

The problem requires implementing a BSTIterator class that allows forward and backward traversal over the in-order sequence of a Binary Search Tree (BST). In-order traversal of a BST visits nodes in ascending order.

leetcodemediumstacktreedesignbinary-search-treebinary-treeiterator
LeetCode 872 - Leaf-Similar Trees

This problem asks us to compare two binary trees based only on their leaf nodes. A leaf node is a node that has no left child and no right child.

leetcodeeasytreedepth-first-searchbinary-tree
LeetCode 1716 - Calculate Money in Leetcode Bank

The problem describes a repeating weekly saving pattern. Hercy deposits money into the LeetCode bank every day, and the amount increases in a structured way. On the very first Monday, he deposits 1 dollar. Each following day in the same week increases by 1.

leetcodeeasymath
LeetCode 1064 - Fixed Point

The problem is asking us to find a "fixed point" in a sorted array of distinct integers. A fixed point is an index i such that the value at that index equals the index itself, i.e., arr[i] == i.

leetcodeeasyarraybinary-search
LeetCode 486 - Predict the Winner

The problem describes a two-player game played on an integer array. Players alternate turns, and during each turn a player may only take a number from one of the two ends of the array. The chosen value is added to that player's score, and the element is removed from the array.

leetcodemediumarraymathdynamic-programmingrecursiongame-theory
LeetCode 1443 - Minimum Time to Collect All Apples in a Tree

The problem is asking for the minimum time required to collect all apples in a tree, where each edge traversal takes 1 s

leetcodemediumhash-tabletreedepth-first-searchbreadth-first-search
LeetCode 953 - Verifying an Alien Dictionary

This problem asks us to verify whether a list of words is sorted according to a custom alphabet order, instead of the normal English alphabetical order. In normal lexicographical ordering, characters are compared from left to right using the standard alphabet.

leetcodeeasyarrayhash-tablestring
LeetCode 63 - Unique Paths II

This problem asks us to count how many different valid paths exist for a robot moving through a grid while avoiding obstacles. The robot starts in the top-left corner of the grid at position (0, 0) and wants to reach the bottom-right corner at position (m - 1, n - 1).

leetcodemediumarraydynamic-programmingmatrix
CF 131E - Yet Another Task with Queens

We are given positions of queens on a chessboard. A queen attacks in eight directions: left, right, up, down, and the four diagonals. A queen does not attack every queen in a direction, only the first one encountered along that ray.

codeforcescompetitive-programmingsortings
LeetCode 253 - Meeting Rooms II

The problem gives us a list of meeting intervals where each interval is represented as [start, end]. Each interval describes the time range during which a meeting occupies a conference room.

leetcodemediumarraytwo-pointersgreedysortingheap-(priority-queue)prefix-sum
LeetCode 1550 - Three Consecutive Odds

This problem asks us to examine a list of integers, arr, and determine whether there exists a sequence of three consecut

leetcodeeasyarray
CF 22C - System Administrator

We are asked to design a network of servers where each server is a node, and each connection between two servers is an undirected edge. There are n servers and we are allowed exactly m connections.

codeforcescompetitive-programminggraphs
LeetCode 1746 - Maximum Subarray Sum After One Operation

The problem gives us an integer array nums, and we must perform exactly one operation on the array. The operation allows us to choose a single index i and replace the value nums[i] with its square, nums[i] nums[i].

leetcodemediumarraydynamic-programming
CF 87C - Interesting Game

We are asked to analyze a two-player game with a single pile of n stones. The players alternate turns, starting with Serozha.

codeforcescompetitive-programmingdpgamesmath
LeetCode 1165 - Single-Row Keyboard

The problem describes a single-row keyboard where each key is positioned at a unique index from 0 to 25. You are given a string keyboard of length 26 that specifies the layout of all lowercase English letters.

leetcodeeasyhash-tablestring
CF 107D - Crime Management

Zeyad wants to commit exactly n crimes in a sequence so that he avoids any punishment. Each crime type is represented by a capital letter, and for some crimes there are conditions describing multiplicities: committing that crime a number of times divisible by its multiplicity…

codeforcescompetitive-programmingdpgraphsmatrices
LeetCode 958 - Check Completeness of a Binary Tree

The problem asks us to determine whether a given binary tree is a complete binary tree. A complete binary tree has a specific structural property: every level, except possibly the last, is completely filled, and in the last level, all nodes appear as far left as possible.

leetcodemediumtreebreadth-first-searchbinary-tree
LeetCode 105 - Construct Binary Tree from Preorder and Inorder Traversal

The problem is asking us to reconstruct a binary tree given two traversal orders: preorder and inorder. In a preorder traversal, nodes are visited in the order: root, left subtree, right subtree.

leetcodemediumarrayhash-tabledivide-and-conquertreebinary-tree
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 1280 - Students and Examinations

This problem asks us to generate a complete report showing how many times every student attended every subject examinati

leetcodeeasydatabase
LeetCode 1462 - Course Schedule IV

This problem gives us a directed acyclic graph representing course dependencies. Each course is a node, and a prerequisi

leetcodemediumdepth-first-searchbreadth-first-searchgraph-theorytopological-sort
CF 84C - Biathlon

We are given a set of circular targets, all lying on the Ox axis, each defined by its center coordinate and radius. Valera shoots multiple times, and each shot has an (x, y) coordinate.

codeforcescompetitive-programmingbinary-searchimplementation
LeetCode 900 - RLE Iterator

This problem asks us to design an iterator over a run-length encoded sequence instead of storing the full sequence explicitly.

leetcodemediumarraydesigncountingiterator
CF 60B - Serial Time!

We are given a three-dimensional grid representing the inside of a plate. The grid has k layers, each layer has n rows and m columns. Every cell is either empty . or blocked . Water starts entering from one specific cell on the top layer.

codeforcescompetitive-programmingdfs-and-similardsu
LeetCode 1041 - Robot Bounded In Circle

This problem asks us to determine whether a robot moving on an infinite two dimensional plane will remain within some bounded region if it repeats a sequence of instructions forever. The robot starts at coordinate (0, 0) facing north.

leetcodemediummathstringsimulation
LeetCode 702 - Search in a Sorted Array of Unknown Size

This problem asks us to search for a target value inside a sorted array, but with an important limitation: we do not know the size of the array, and we cannot access the array directly. Instead of normal array indexing, we interact with the array through an ArrayReader interface.

leetcodemediumarraybinary-searchinteractive
CF 6B - President's Office

The office is represented as a rectangular grid. Every uppercase letter represents part of a desk, and all cells with the same letter belong to the same rectangular desk. The president’s desk color is given as c.

codeforcescompetitive-programmingimplementation
LeetCode 462 - Minimum Moves to Equal Array Elements II

This problem asks us to determine the minimum number of moves required to make all elements in an integer array equal, where a move consists of incrementing or decrementing a single element by 1.

leetcodemediumarraymathsorting
LeetCode 1618 - Maximum Font to Fit a Sentence in a Screen

In this problem, we are given a string text that must be displayed on a single line inside a screen with width w and hei

leetcodemediumarraystringbinary-searchinteractive
LeetCode 1949 - Strong Friendship

The problem gives us a table named Friendship, where every row represents a friendship relationship between two users. E

leetcodemediumdatabase
LeetCode 83 - Remove Duplicates from Sorted List

This problem asks us to remove duplicate values from a sorted singly linked list so that every distinct value appears exactly once.

leetcodeeasylinked-list
LeetCode 1644 - Lowest Common Ancestor of a Binary Tree II

This problem asks us to find the lowest common ancestor (LCA) of two given nodes, p and q, in a binary tree, under the c

leetcodemediumtreedepth-first-searchbinary-tree
LeetCode 852 - Peak Index in a Mountain Array

This problem gives us a special type of array called a mountain array. A mountain array strictly increases until it reaches a single peak element, then strictly decreases afterward. In other words, there exists some index i such that: - arr[0] < arr[1] < ...

leetcodemediumarraybinary-search
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 423 - Reconstruct Original Digits from English

The problem asks us to reconstruct digits from a jumbled string of English letters representing numbers from 0 to 9.

leetcodemediumhash-tablemathstring
LeetCode 1798 - Maximum Number of Consecutive Values You Can Make

The problem gives us an array of coin values, where each coin can be used at most once. We are asked to determine the maximum number of consecutive integer values that can be formed starting from 0.

leetcodemediumarraygreedysorting
CF 57B - Martian Architecture

Each construction describes a staircase placed on a one-dimensional line of cells. A staircase starts at cell l, ends at cell r, and adds heights in an arithmetic progression.

codeforcescompetitive-programmingimplementation
LeetCode 769 - Max Chunks To Make Sorted

This problem is asking us to determine the maximum number of contiguous chunks into which we can split an array such that sorting each chunk individually and concatenating them results in a fully sorted array.

leetcodemediumarraystackgreedysortingmonotonic-stack
CF 128C - Games with Rectangle

We start with a rectangle drawn on grid paper. Only the border matters, not the interior. Players repeatedly draw a strictly smaller rectangle inside the previous one.

codeforcescompetitive-programmingcombinatoricsdp
LeetCode 1666 - Change the Root of a Binary Tree

This problem asks us to reroot a binary tree at a given leaf node. Normally, a binary tree has a single root, and every node points downward to its children. In this problem, each node also contains a parent pointer, which allows traversal upward toward the root.

leetcodemediumtreedepth-first-searchbinary-tree
LeetCode 1108 - Defanging an IP Address

The problem asks us to transform a valid IPv4 address into its "defanged" version. A defanged IP address is created by replacing every period character "." with the string "[.]". An IPv4 address consists of four numeric segments separated by periods. For example, "1.1.1.

leetcodeeasystring
CF 119D - String Transformation

We are given two strings, a and b, of equal length up to one million characters. The task is to find indices i and j in a such that if we perform a specific transformation, we get b.

codeforcescompetitive-programminghashingstrings
LeetCode 1558 - Minimum Numbers of Function Calls to Make Target Array

This problem asks us to transform an initial array arr of zeros into a target array nums using a minimal number of operations. There are two allowed operations: incrementing any single element of the array by 1, or doubling all elements of the array.

leetcodemediumarraygreedybit-manipulation
LeetCode 551 - Student Attendance Record I

The problem gives us a string s where each character represents a student's attendance record for one day. There are only three possible characters: - 'A' means the student was absent. - 'L' means the student was late. - 'P' means the student was present.

leetcodeeasystring
CF 52B - Right Triangles

We are given a rectangular grid where each cell is either empty or marked with . Every cell represents a point located at the center of that cell. We need to count how many right triangles can be formed such that:

codeforcescompetitive-programmingcombinatorics
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
LeetCode 359 - Logger Rate Limiter

The problem asks us to design a logging system that controls how frequently identical messages can be printed. Each message is associated with a timestamp, and the same message is only allowed to be printed once every 10 seconds.

leetcodeeasyhash-tabledesigndata-stream
CF 63C - Bulls and Cows

We are playing the classic Bulls and Cows game with four-digit numbers whose digits are all distinct. Leading zeroes are allowed, so 0123 is valid, but repeated digits such as 0012 or 1223 are not. Each previous guess comes with two values.

codeforcescompetitive-programmingbrute-forceimplementation
LeetCode 1323 - Maximum 69 Number

The problem gives us a positive integer num that contains only the digits 6 and 9. We are allowed to change at most one

leetcodeeasymathgreedy
LeetCode 1591 - Strange Printer II

In this problem, we are given a final colored matrix called targetGrid. We need to determine whether a strange printer could have produced this grid under two unusual restrictions.

leetcodehardarraygraph-theorytopological-sortmatrix
LeetCode 1682 - Longest Palindromic Subsequence II

The problem is asking us to find the length of the longest good palindromic subsequence in a given string s. A good pali

leetcodemediumstringdynamic-programming
CF 44E - Anfisa the Monkey

We are given a string of lowercase letters that contains no spaces. The task is to split this string into exactly k consecutive pieces. Every piece must have length between a and b, inclusive. The order of characters cannot change. We are only deciding where to cut the string.

codeforcescompetitive-programmingdp
LeetCode 2067 - Number of Equal Count Substrings

The problem asks us to count the number of substrings in a string s such that every unique character in the substring occurs exactly count times. A substring is a contiguous segment of the string, so we are only considering consecutive characters.

leetcodemediumhash-tablestringsliding-windowcounting
CF 67D - Optical Experiment

Each ray enters the box through one hole on the left side and exits through one hole on the right side. The order of holes on both sides matters.

codeforcescompetitive-programmingbinary-searchdata-structuresdp
LeetCode 970 - Powerful Integers

This problem asks us to generate all integers that can be written in the form: where: - i = 0 - j = 0 - the resulting value is less than or equal to bound The inputs are three integers: - x, the base of the first exponential term - y, the base of the second exponential term -…

leetcodemediumhash-tablemathenumeration
LeetCode 1677 - Product's Worth Over Invoices

The problem asks us to calculate aggregate monetary information for each product based on invoices. We have two tables:

leetcodeeasydatabase
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
LeetCode 434 - Number of Segments in a String

The problem asks us to count how many separate word-like groups exist inside a string. In this problem, a "segment" is defined as a continuous sequence of characters that are not spaces.

leetcodeeasystring