brain

tamnd's digital brain — notes, problems, research

42641 notes

LeetCode 2708 - Maximum Strength of a Group

The problem asks us to select a non-empty subset of integers from a given array nums such that the product of the numbers in the subset is maximized. Each number represents a student’s exam score, and the subset represents a group of students.

leetcodemediumarraydynamic-programmingbacktrackinggreedybit-manipulationsortingenumeration
LeetCode 3386 - Button with Longest Push Time

The problem gives us a sequence of keyboard button press events. Each event is represented as: Here: - index is the identifier of the button that was pressed. - time is the moment when the press happened.

leetcodeeasyarray
LeetCode 2932 - Maximum Strong Pair XOR I

The problem gives us an integer array nums, and we must choose two numbers x and y from the array such that they form a strong pair.

leetcodeeasyarrayhash-tablebit-manipulationtriesliding-window
LeetCode 2536 - Increment Submatrices by One

LeetCode 2536: Increment Submatrices by One (Medium)

leetcodemediumarraymatrixprefix-sum
LeetCode 2413 - Smallest Even Multiple

The problem asks us to find the smallest positive integer that is a multiple of both 2 and a given positive integer n. In other words, we are looking for the least common multiple (LCM) of 2 and n. The input n is guaranteed to be between 1 and 150, which is a very small range.

leetcodeeasymathnumber-theory
CF 446C - DZY Loves Fibonacci Numbers

We are given an array of integers and need to support two types of queries efficiently. The first type requires adding Fibonacci numbers to a contiguous subarray: for indices from l to r, we add F₁ to the element at l, F₂ to the element at l+1, up to F{r-l+1} at position r.

codeforcescompetitive-programmingdata-structuresmathnumber-theory
LeetCode 3377 - Digit Operations to Make Two Integers Equal

The problem asks us to transform one integer n into another integer m by repeatedly modifying individual digits of n. At each step, we can increase a digit that is not 9 or decrease a digit that is not 0.

leetcodemediummathgraph-theoryheap-(priority-queue)number-theoryshortest-path
LeetCode 2320 - Count Number of Ways to Place Houses

The problem presents a street with n plots on each side, for a total of 2 n plots. The goal is to count the number of ways to place houses on these plots such that no two houses are adjacent on the same side of the street.

leetcodemediumdynamic-programming
LeetCode 2236 - Root Equals Sum of Children

This problem gives us a binary tree that always contains exactly three nodes. There is one root node, one left child, and one right child. We must determine whether the value stored in the root node is equal to the sum of the values stored in its two children.

leetcodeeasytreebinary-tree
LeetCode 2641 - Cousins in Binary Tree II

The problem gives us the root of a binary tree and asks us to replace every node’s value with the sum of all of its cousins’ values.

leetcodemediumhash-tabletreedepth-first-searchbreadth-first-searchbinary-tree
CF 424C - Magic Formulas

Codeforces 424C: Magic Formulas

codeforcescompetitive-programmingmath
LeetCode 3172 - Second Day Verification

The problem requires identifying users who verified their signup exactly on the second day after registering. We have two tables: emails and texts. The emails table contains the emailid, the userid, and the signupdate.

leetcodeeasydatabase
LeetCode 2327 - Number of People Aware of a Secret

The problem describes how a secret spreads over time. On day 1, exactly one person knows the secret. Every person who learns the secret behaves according to two rules: 1. They must wait delay days before they can begin sharing the secret. 2.

leetcodemediumdynamic-programmingqueuesimulation
CF 187E - Heaven Tour

We have n people placed on a line at strictly increasing coordinates. PMP starts at person s, which immediately counts as visited. Every later move must go either strictly left or strictly right, depending on the ticket used for that move.

codeforcescompetitive-programmingdata-structuresgreedy
LeetCode 3167 - Better Compression of String

The problem gives us a compressed string where every character is immediately followed by its frequency. For example, the string "a3b2" represents the original expanded string "aaabb". However, the input compression is not guaranteed to be optimal.

leetcodemediumhash-tablestringsortingcounting
LeetCode 3328 - Find Cities in Each State II

The problem gives us a database table named cities, where each row contains a state name and a city name. The pair (state, city) is guaranteed to be unique, which means the same city will not appear twice for the same state. We must generate a report for qualifying states.

leetcodemediumdatabase
CF 225B - Well-known Numbers

We are given two integers, s and k. The task is to express s as a sum of distinct numbers taken from the k-bonacci sequence. The sequence behaves like Fibonacci, but instead of summing the previous two values, each term is the sum of the previous k terms.

codeforcescompetitive-programmingbinary-searchgreedynumber-theory
CF 263B - Squares

Codeforces 263B: Squares

codeforcescompetitive-programminggreedyimplementationsortings
LeetCode 3093 - Longest Common Suffix Queries

The problem asks us to process a set of suffix matching queries efficiently. We are given two arrays: - wordsContainer, which contains candidate strings - wordsQuery, which contains query strings For every query string, we must find the index of the string in wordsContainer…

leetcodehardarraystringtrie
LeetCode 2814 - Minimum Time Takes to Reach Destination Without Drowning

This problem takes place on a two-dimensional grid where each cell represents a type of terrain. The grid contains: - "S": your starting position. - "D": the destination you want to reach. - ".": an empty cell that can be walked on. - "X": a stone cell that cannot be entered.

leetcodehardarraybreadth-first-searchmatrix
LeetCode 2741 - Special Permutations

The problem asks us to count the number of special permutations of a given array of distinct positive integers nums.

leetcodemediumarraydynamic-programmingbit-manipulationbitmask
LeetCode 3252 - Premier League Table Ranking II

The problem asks us to compute a Premier League-style ranking table from a TeamStats table, which contains each team's matches played, wins, draws, and losses. We are required to calculate three additional columns for each team: points, position, and tier.

leetcodemediumdatabase
LeetCode 2727 - Is Object Empty

This problem asks us to determine if a given object or array is empty. In JavaScript terms, an object is empty if it has no key-value pairs, while an array is empty if it has no elements.

leetcodeeasy
CF 305D - Olya and Graph

We are given a directed acyclic graph with vertices numbered from 1 to n, where every edge goes from a smaller-numbered vertex to a larger-numbered vertex. Some edges already exist, and we are allowed to add more edges under certain constraints.

codeforcescompetitive-programmingcombinatoricsmath
CF 413D - 2048

We process a sequence of tiles, each tile being either 2 or 4. A tile starts far to the right and slides left. When it touches an equal value, the two merge into a doubled value and the new tile keeps moving.

codeforcescompetitive-programmingbitmasksdp
LeetCode 2940 - Find Building Where Alice and Bob Can Meet

You are given an array heights, where each index represents a building and the value represents that building's height.

leetcodehardarraybinary-searchstackbinary-indexed-treesegment-treeheap-(priority-queue)monotonic-stack
LeetCode 1868 - Product of Two Run-Length Encoded Arrays

This problem asks us to multiply two arrays that are already stored in run-length encoded form, without fully expanding them into normal arrays. A run-length encoded array stores consecutive repeated values compactly.

leetcodemediumarraytwo-pointers
LeetCode 3157 - Find the Level of Tree with Minimum Sum

The problem gives us the root of a binary tree, where every node contains a positive integer value. Our task is to determine which level of the tree has the smallest sum of node values.

leetcodemediumtreedepth-first-searchbreadth-first-searchbinary-tree
CF 218A - Mountain Scenery

We are given a polyline representing mountain peaks. The polyline has 2n + 1 vertices, with even-indexed vertices (2, 4, 6, ..., 2n) representing peaks. In the initial picture, each peak is strictly higher than its neighbors, i.e., for every even i, y[i-1] < y[i] y[i+1].

codeforcescompetitive-programmingbrute-forceconstructive-algorithmsimplementation
LeetCode 2237 - Count Positions on Street With Required Brightness

The problem describes a street represented by positions from 0 to n - 1. There are multiple street lamps, each defined by its position and range. A lamp at position p with range r illuminates all positions from max(0, p - r) to min(n - 1, p + r), inclusive.

leetcodemediumarrayprefix-sum
CF 402D - Upgrading Array

We are given an array of positive integers and a set of "bad" prime numbers. Every other prime not in the bad set is implicitly "good." Each number in the array contributes to a total "beauty" score determined by its prime factorization.

codeforcescompetitive-programmingdpgreedymathnumber-theory
LeetCode 2516 - Take K of Each Character From Left and Right

The problem asks us to determine the minimum number of characters to take from either end of a string s consisting only of the letters 'a', 'b', and 'c' so that we collect at least k of each character.

leetcodemediumhash-tablestringsliding-window
LeetCode 2950 - Number of Divisible Substrings

The problem asks us to analyze a given string word where each lowercase English letter is mapped to a digit according to a classic phone keypad scheme.

leetcodemediumhash-tablestringcountingprefix-sum
LeetCode 3320 - Count The Number of Winning Sequences

We are given a string s representing Alice’s moves across n rounds of a game. Each character corresponds to one creature: - 'F' = Fire Dragon - 'W' = Water Serpent - 'E' = Earth Golem In every round, Alice and Bob each choose one creature simultaneously.

leetcodehardstringdynamic-programming
LeetCode 2767 - Partition String Into Minimum Beautiful Substrings

The problem asks us to partition a given binary string s into the minimum number of substrings such that each substring is beautiful. A substring is beautiful if it represents a power of 5 in decimal and does not have leading zeros.

leetcodemediumhash-tablestringdynamic-programmingbacktracking
CF 270A - Fancy Fence

We are asked to determine whether a robot, which can only make fence corners at a fixed angle a, can construct a regular polygon. A regular polygon is defined as a closed shape with all sides and all angles equal.

codeforcescompetitive-programminggeometryimplementationmath
CF 241B - Friends

We have an array of friend attractiveness values. Every unordered pair of distinct friends produces one possible picture, and the value of that picture is the xor of the two attractiveness values.

codeforcescompetitive-programmingbinary-searchbitmasksdata-structuresmath
LeetCode 1945 - Sum of Digits of String After Convert

This problem asks us to take a string of lowercase English letters and convert it into a numeric value, then repeatedly transform that number by summing its digits.

leetcodeeasystringsimulation
LeetCode 2672 - Number of Adjacent Elements With the Same Color

The problem gives us an array called colors of length n. Initially, every element is 0, which represents an uncolored position. We then process a sequence of queries.

leetcodemediumarray
LeetCode 2805 - Custom Interval

This problem asks us to implement a custom version of setInterval, but with a key difference. Instead of using a fixed delay between executions, the delay grows linearly according to the formula: where count starts at 0 and increases after every execution.

leetcodemedium
IMO 1962 Problem 3

The motion takes place on two adjacent faces of the cube.

imomathematicsolympiad
IMO 1961 Problem 6

The problem asks for the locus of the centroid of a triangle whose vertices are the midpoints of three segments joining fixed points above a plane to arbitrary points on the plane.

imomathematicsolympiad
IMO 1960 Problem 6

The geometry becomes transparent after reducing the three-dimensional configuration to a two-dimensional meridian section through the axis of the cone.

imomathematicsolympiad
IMO 1960 Problem 5

The problem asks for two loci inside a cube.

imomathematicsolympiad
IMO 2024 Problem 6

We are asked to analyze functions $f:\mathbb{Q} \to \mathbb{Q}$ satisfying the following property: for every $x,y \in \mathbb{Q}$, at least one of the two identities

imomathematicsolympiad
IMO 2024 Problem 5

The board has $2024$ rows and $2023$ columns.

imomathematicsolympiad
IMO 2024 Problem 4

We must prove

imomathematicsolympiad
IMO 2024 Problem 3

For each $n>N$, the sequence satisfies

imomathematicsolympiad
IMO 2024 Problem 1

For each real number $\alpha$, define

imomathematicsolympiad
LeetCode 630 - Course Schedule III

The problem gives a list of online courses, where each course is represented as [duration, lastDay]. The duration tells us how many consecutive days are required to complete the course. The lastDay tells us the latest possible day by which the course must be finished.

leetcodehardarraygreedysortingheap-(priority-queue)
LeetCode 1076 - Project Employees II

This problem asks us to identify the project or projects that have the largest number of employees assigned to them. We are given two database tables. The Project table stores relationships between projects and employees.

leetcodeeasydatabase
LeetCode 1589 - Maximum Sum Obtained of Any Permutation

The problem gives us an integer array nums and a collection of range requests. Each request [start, end] asks for the su

leetcodemediumarraygreedysortingprefix-sum
LeetCode 1842 - Next Palindrome Using Same Digits

The input is a numeric string num that is guaranteed to already be a palindrome. The task is to rearrange its digits to create another palindrome that is strictly larger than the original number, while also being the smallest such palindrome possible.

leetcodehardtwo-pointersstring
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
CF 44G - Shooting Gallery

The problem can be restated as simulating bullets flying along the positive _Z_ axis at given coordinates on a 2D shooting plane (_XOY_). Each bullet may hit one of multiple rectangular targets floating at distinct heights along the _Z_ axis.

codeforcescompetitive-programmingdata-structuresimplementation
LeetCode 217 - Contains Duplicate

The problem gives an integer array nums and asks whether any number appears more than once. If at least one value is repeated, we return true. If every value appears exactly once, we return false. The input is a list of integers.

leetcodeeasyarrayhash-tablesorting
LeetCode 1696 - Jump Game VI

The problem gives us an integer array nums and a maximum jump distance k. We start at index 0, and from any position i,

leetcodemediumarraydynamic-programmingqueueheap-(priority-queue)monotonic-queue
LeetCode 1612 - Check If Two Expression Trees are Equivalent

The problem asks us to determine whether two binary expression trees are equivalent, where equivalence is defined as the trees representing the same arithmetic expression, modulo the order of addition since addition is commutative.

leetcodemediumhash-tabletreedepth-first-searchbinary-treecounting
LeetCode 185 - Department Top Three Salaries

This is a SQL database problem where we need to identify the employees who belong to the top three unique salaries within each department.

leetcodeharddatabase
CF 134B - Pairs of Numbers

We are asked to start with the number pair (1,1) and reach a pair where at least one of the numbers equals a given target n. At each step, we can add one number to the other to form a new pair. Concretely, if our current pair is (a, b), the next pair can be (a+b, b) or (a, a+b).

codeforcescompetitive-programmingbrute-forcedfs-and-similarmathnumber-theory
LeetCode 451 - Sort Characters By Frequency

The problem asks us to rearrange the characters of a string so that characters with higher frequency appear before characters with lower frequency. The output string must group identical characters together, and those groups must appear in descending order of occurrence count.

leetcodemediumhash-tablestringsortingheap-(priority-queue)bucket-sortcounting
LeetCode 522 - Longest Uncommon Subsequence II

The problem asks us to find the length of the longest string in the array that is not a subsequence of any other string in the same array. A subsequence is formed by deleting zero or more characters from a string without changing the order of the remaining characters.

leetcodemediumarrayhash-tabletwo-pointersstringsorting
LeetCode 455 - Assign Cookies

This problem asks us to maximize the number of children who can be satisfied with the available cookies. Each child has a greed factor, and each cookie has a size. A child becomes content only if they receive a cookie whose size is greater than or equal to their greed factor.

leetcodeeasyarraytwo-pointersgreedysorting
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 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 1422 - Maximum Score After Splitting a String

The problem gives us a binary string s, meaning the string contains only the characters '0' and '1'. We must split this string into two non-empty parts, a left substring and a right substring.

leetcodeeasystringprefix-sum
LeetCode 1294 - Weather Type in Each Country

This problem asks us to determine the weather type for each country during November 2019, based on the average weatherst

leetcodeeasydatabase
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 365 - Water and Jug Problem

The problem gives us two water jugs with capacities x and y. We can perform only three types of operations: - Fill a jug completely - Empty a jug completely - Pour water from one jug into the other until either the source jug becomes empty or the destination jug becomes full…

leetcodemediummathdepth-first-searchbreadth-first-search
CF 53D - Physical Education

We have two arrays representing the order of students in a line. Array a is the desired arrangement, and array b is the current arrangement. In one operation we may swap two neighboring students. We must output any sequence of adjacent swaps that transforms b into a.

codeforcescompetitive-programmingsortings
LeetCode 1154 - Day of the Year

The problem asks us to compute the ordinal day number of a year given a date in the format YYYY-MM-DD. For example, January 1st is always day 1, January 2nd is day 2, and December 31st is either day 365 or 366 depending on whether the year is a leap year.

leetcodeeasymathstring
LeetCode 294 - Flip Game II

This problem describes a two-player impartial game played on a string consisting only of '+' and '-' characters. A valid move consists of selecting any pair of consecutive "++" characters and flipping them into "--". The players alternate turns.

leetcodemediummathdynamic-programmingbacktrackingmemoizationgame-theory
LeetCode 1056 - Confusing Number

The problem asks us to determine whether a given integer becomes a different valid number after being rotated by 180 degrees. Not every digit remains valid after rotation.

leetcodeeasymath
CF 42D - Strange town

We are asked to construct a fully connected graph of _N_ tourist attractions, where each road has a distinct positive integer cost not exceeding 1000.

codeforcescompetitive-programmingconstructive-algorithmsmath
LeetCode 373 - Find K Pairs with Smallest Sums

The problem gives us two sorted integer arrays, nums1 and nums2, and asks us to return the k pairs with the smallest sums. A pair is formed by taking one element from nums1 and one element from nums2.

leetcodemediumarrayheap-(priority-queue)
LeetCode 605 - Can Place Flowers

The problem gives us a binary array called flowerbed, where: - 0 represents an empty plot - 1 represents a plot that already contains a flower We are also given an integer n, which represents how many new flowers we want to plant.

leetcodeeasyarraygreedy
LeetCode 1348 - Tweet Counts Per Frequency

The problem is asking us to design a system that tracks tweets by their timestamp and allows querying the number of tweets in specific time intervals, split according to a frequency (minute, hour, or day).

leetcodemediumhash-tablestringbinary-searchdesignsortingordered-set
CF 83C - Track

We have a rectangular grid. Each cell contains either a terrain type represented by a lowercase letter, the start cell S, or the target cell T. We may move in four directions between side-adjacent cells. Every move costs exactly one minute. The path must start at S and end at T.

codeforcescompetitive-programminggraphsgreedyshortest-paths
CF 14D - Two Paths

We are given a tree of n cities, meaning each city is connected in such a way that there is exactly one simple path between any two cities. Roads are undirected, and each road has a length of 1.

codeforcescompetitive-programmingdfs-and-similardpgraphsshortest-pathstreestwo-pointers
LeetCode 736 - Parse Lisp Expression

The problem asks us to evaluate a Lisp-like expression represented as a string. The expression can contain integers, variables, and three special operations: let, add, and mult. An expression evaluates to a single integer value.

leetcodehardhash-tablestringstackrecursion
LeetCode 374 - Guess Number Higher or Lower

The problem describes a classic interactive guessing game. A hidden number called pick is chosen somewhere in the range from 1 to n, inclusive. We are not allowed to access pick directly.

leetcodeeasybinary-searchinteractive
LeetCode 634 - Find the Derangement of An Array

The problem asks us to count how many permutations of the numbers 1 through n are valid derangements. A derangement is a permutation where no element remains in its original position. For example, when n = 3, the original array is [1, 2, 3].

leetcodemediummathdynamic-programmingcombinatorics
LeetCode 3053 - Classifying Triangles by Lengths

The problem requires classifying triangles based on the lengths of their three sides, represented by the columns A, B, a

leetcodeeasydatabase
LeetCode 758 - Bold Words in String

The problem gives us two inputs: an array of strings called words, and a target string s. Every occurrence of every word from words inside s must become bold by surrounding that substring with <b and </b tags.

leetcodemediumarrayhash-tablestringtriestring-matching
CF 94A - Restoring Password

We are given an encrypted password represented as a binary string of length 80. The original password had exactly 8 decimal digits, and each digit was encoded into a block of 10 binary characters.

codeforcescompetitive-programmingimplementationstrings
LeetCode 725 - Split Linked List in Parts

The problem gives us the head of a singly linked list and an integer k. We must divide the linked list into exactly k consecutive parts while preserving the original order of nodes. The important requirement is that the parts should be as evenly sized as possible.

leetcodemediumlinked-list
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
CF 68D - Half-decay tree

We have a complete binary tree of height h. Every vertex may store some number of electrons, and queries gradually add more electrons to vertices. A decay operation chooses one leaf uniformly at random and deletes every edge on the path from the root to that leaf.

codeforcescompetitive-programmingdata-structuresdivide-and-conquerdpmathprobabilities
LeetCode 1492 - The kth Factor of n

The problem asks us to find the kth factor of a positive integer n, where the factors are ordered in ascending order. A

leetcodemediummathnumber-theory
LeetCode 907 - Sum of Subarray Minimums

The problem asks us to compute the sum of the minimum value of every possible contiguous subarray of a given array. For an array arr, every contiguous slice of the array is considered a subarray. For each subarray, we determine its minimum element.

leetcodemediumarraydynamic-programmingstackmonotonic-stack
LeetCode 2003 - Smallest Missing Genetic Value in Each Subtree

This problem asks us to compute, for every node in a rooted tree, the smallest positive integer that does not appear in the subtree rooted at that node. We are given two arrays: parents describes the tree structure, and nums contains distinct genetic values assigned to each node.

leetcodehardarraydynamic-programmingtreedepth-first-searchunion-find
CF 42E - Baldman and the military

We are asked to prepare a set of additional undirected edges, called wormholes, on top of an unknown tunnel system.

codeforcescompetitive-programmingdfs-and-similargraphstrees
LeetCode 1065 - Index Pairs of a String

The problem gives us a string called text and a list of dictionary words called words. We must find every substring inside text that exactly matches one of the words in the dictionary.

leetcodeeasyarraystringtriesorting
LeetCode 1592 - Rearrange Spaces Between Words

The problem requires rearranging spaces in a given string text so that all words are separated by the maximum possible e

leetcodeeasystring
LeetCode 1469 - Find All The Lonely Nodes

This problem asks us to traverse a binary tree and identify every node that is considered "lonely". A node is lonely if

leetcodeeasytreedepth-first-searchbreadth-first-searchbinary-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 89A - Robbery

The bank stores diamonds in a row of cells. After every minute, the security system checks the sums of every adjacent pair: $$a1 + a2, a2 + a3, dots, a{n-1} + an$$ If any of these sums changes compared to the previous check, the alarm triggers.

codeforcescompetitive-programminggreedy
LeetCode 1298 - Maximum Candies You Can Get from Boxes

The problem asks us to determine the maximum number of candies we can collect from a set of boxes with varying accessibi

leetcodehardarraybreadth-first-searchgraph-theory
LeetCode 496 - Next Greater Element I

The problem is asking us to find the next greater element for each element in nums1 within another array nums2. Formally, for each element in nums1, we need to locate its position in nums2 and then find the first element to its right in nums2 that is greater than itself.

leetcodeeasyarrayhash-tablestackmonotonic-stack
LeetCode 1404 - Number of Steps to Reduce a Number in Binary Representation to One

The problem gives us a binary number represented as a string s. Our task is to determine how many operations are require

leetcodemediumstringbit-manipulationsimulation