brain

tamnd's digital brain — notes, problems, research

43815 notes

LeetCode 2457 - Minimum Addition to Make Integer Beautiful

The problem asks us to transform a given integer n into a beautiful integer by adding the smallest non-negative integer x. An integer is defined as beautiful if the sum of its digits is less than or equal to a given target.

leetcodemediummathgreedy
CF 141B - Hopscotch

We are asked to determine whether a stone thrown onto a hopscotch court lands strictly inside a square, and if so, to identify which square. The court is constructed from squares of side length a, arranged in rows with a repeating 1-1-2-1-2 pattern.

codeforcescompetitive-programminggeometrymath
LeetCode 3349 - Adjacent Increasing Subarrays Detection I

The problem gives us an integer array nums and an integer k. We need to determine whether the array contains two adjacent subarrays, each of length k, such that both subarrays are strictly increasing.

leetcodeeasyarray
LeetCode 2755 - Deep Merge of Two Objects

Here is the complete technical solution guide for LeetCode 2755 following your requested format. The problem asks us to deep merge two JSON values, obj1 and obj2. The merging rules depend on the type of the values at each position in the objects or arrays.

leetcodemedium
CF 191E - Thwarting Demonstrations

We have an array of soldier reliabilities. Every contiguous subarray represents one possible police group. The general always chooses the strongest unused group first, meaning all subarray sums are sorted in descending order and picked one by one.

codeforcescompetitive-programmingbinary-searchdata-structurestrees
LeetCode 2112 - The Airport With the Most Traffic

This problem asks us to find the airport(s) with the most traffic using a table of flights. Each row of the Flights table represents a direct connection from departureairport to arrivalairport along with the number of flights flightscount for that route.

leetcodemediumdatabase
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
CF 221B - Little Elephant and Numbers

We are asked to count divisors of a given positive integer x that share at least one digit with x. In other words, we examine every number d that divides x evenly and check whether there exists a digit appearing both in x and in d.

codeforcescompetitive-programmingimplementation
LeetCode 1962 - Remove Stones to Minimize the Total

The problem gives us an array called piles, where each element represents the number of stones in a pile. We are also given an integer k, representing the exact number of operations we must perform. In one operation, we choose a pile and remove floor(pile / 2) stones from it.

leetcodemediumarraygreedyheap-(priority-queue)
LeetCode 3284 - Sum of Consecutive Subarrays

The problem asks us to compute the sum of all consecutive subarrays in a given integer array nums. A consecutive subarray is defined as one where each element differs from the previous by exactly 1 or -1.

leetcodemediumarraytwo-pointersdynamic-programming
CF 137D - Palindromes

We are given a string and an integer k. We may change any characters we want, and the goal is to transform the string into a concatenation of at most k palindromes while minimizing the number of modified characters. The partition boundaries are not fixed.

codeforcescompetitive-programmingdpstrings
LeetCode 1862 - Sum of Floored Pairs

The problem asks us to calculate the sum of the integer division results, floor(nums[i] / nums[j]), for every pair of elements (i, j) in a given array nums. Here, floor() represents the largest integer less than or equal to the division result.

leetcodehardarraymathbinary-searchcountingenumerationprefix-sum
LeetCode 2109 - Adding Spaces to a String

The problem requires us to insert spaces into a given string s at specific positions described by the array spaces. Each element in spaces represents an index in the string before which a space should be inserted.

leetcodemediumarraytwo-pointersstringsimulation
LeetCode 2669 - Count Artist Occurrences On Spotify Ranking List

This problem provides a database table named Spotify that contains information about songs appearing in a Spotify ranking list.

leetcodeeasydatabase
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 296 - Best Meeting Point

The problem gives us a two-dimensional binary grid where each cell contains either 0 or 1. A value of 1 represents the home location of a friend, while 0 represents an empty cell.

leetcodehardarraymathsortingmatrix
LeetCode 431 - Encode N-ary Tree to Binary Tree

This problem asks us to design a reversible transformation between two different tree structures: - An N-ary tree, where each node can have any number of children - A binary tree, where each node has at most two children The important requirement is not how the encoding looks…

leetcodehardtreedepth-first-searchbreadth-first-searchdesignbinary-tree
LeetCode 483 - Smallest Good Base

The problem is asking us to find the smallest integer k = 2 such that a given number n can be represented in base k with all digits equal to 1. In other words, we want n to be a sum of consecutive powers of k, like 1 + k + k^2 + ... + k^(m-1) for some integer m = 2.

leetcodehardmathbinary-search
LeetCode 1075 - Project Employees I

This problem provides two database tables, Project and Employee. The Project table represents which employees are assigned to which projects. Each row contains a projectid and an employeeid.

leetcodeeasydatabase
LeetCode 59 - Spiral Matrix II

The problem asks us to generate an n x n matrix and fill it with numbers from 1 to n^2 in spiral order. A spiral order traversal means we begin at the top-left corner and move in a clockwise pattern: 1. Move left to right across the top row 2.

leetcodemediumarraymatrixsimulation
LeetCode 1419 - Minimum Number of Frogs Croaking

The problem asks us to determine the minimum number of frogs needed to produce a given sequence of croaks represented by

leetcodemediumstringcounting
LeetCode 415 - Add Strings

The problem asks us to add two non-negative integers where each integer is given as a string instead of a numeric type. The goal is to return the resulting sum as another string. For example, if the inputs are "11" and "123", we should return "134".

leetcodeeasymathstringsimulation
CF 123D - String

We are given a string s. For every substring x of s, we look at all positions where x appears inside s. Suppose these occurrences start at positions: $$p1 < p2 < dots < pk$$ The function F(s, x) counts how many contiguous segments we can choose from this ordered list of…

codeforcescompetitive-programmingstring-suffix-structures
LeetCode 390 - Elimination Game

The problem gives us a sorted list containing every integer from 1 to n. We repeatedly eliminate numbers in alternating directions until only one number remains.

leetcodemediummathrecursion
CF 101D - Castle

We are given a weighted tree rooted at hall 1, where Gerald starts. The treasure is hidden uniformly at random in one of the other halls. Gerald only discovers the treasure when he first enters the correct hall.

codeforcescompetitive-programmingdpgreedyprobabilitiessortingstrees
LeetCode 855 - Exam Room

This problem requires designing a simulation for an exam room seating arrangement. We have n seats in a single row, labeled from 0 to n - 1. Students enter one by one, and each student chooses a seat such that the distance to the closest occupied seat is maximized.

leetcodemediumdesignheap-(priority-queue)ordered-set
LeetCode 516 - Longest Palindromic Subsequence

The problem asks us to determine the length of the longest palindromic subsequence within a given string s. A palindromic subsequence is a sequence of characters that reads the same forwards and backwards and can be obtained by deleting zero or more characters from the…

leetcodemediumstringdynamic-programming
CF 129B - Students and Shoelaces

We can model the students and shoelaces as an undirected graph. Each student is a vertex, and every shoelace between two students is an edge. In one round, every student whose degree is exactly 1 gets removed at the same time.

codeforcescompetitive-programmingbrute-forcedfs-and-similargraphsimplementation
LeetCode 866 - Prime Palindrome

This problem asks us to find the smallest number greater than or equal to n that satisfies two properties simultaneously: 1. The number must be a palindrome. 2. The number must be prime. A palindrome is a number that reads the same forward and backward.

leetcodemediummathnumber-theory
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 17C - Balance

We are given a string consisting of characters a, b, and c, and we are allowed to repeatedly perform two types of operations: copy the left character of any adjacent pair onto the right, or copy the right character onto the left.

codeforcescompetitive-programmingdp
CF 29B - Traffic Lights

A car starts at point A and moves along a straight road toward point B. The total distance is l meters, and the car always moves at a fixed speed v. Somewhere along the road, exactly d meters from the start, there is a traffic light.

codeforcescompetitive-programmingimplementation
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
LeetCode 174 - Dungeon Game

This problem asks us to determine the minimum initial health a knight needs in order to safely travel through a dungeon and rescue a princess.

leetcodehardarraydynamic-programmingmatrix
LeetCode 999 - Available Captures for Rook

The problem gives us an 8 x 8 chessboard represented as a matrix of characters. Each cell contains one of four possible values: - 'R' represents the white rook - 'p' represents a black pawn - 'B' represents a white bishop - '.

leetcodeeasyarraymatrixsimulation
LeetCode 1032 - Stream of Characters

The problem asks us to design a data structure that processes a stream of characters one at a time. After each newly added character, we must determine whether any suffix of the stream matches one of the words from a predefined dictionary.

leetcodehardarraystringdesigntriedata-stream
CF 8D - Two Friends

We have three points on a plane: the cinema, the house, and the shop.

codeforcescompetitive-programmingbinary-searchgeometry
LeetCode 1141 - User Activity for the Past 30 Days I

This problem asks us to compute the number of distinct active users for each day within a fixed 30 day window. The window ends on 2019-07-27, inclusive, which means we only consider activity dates from 2019-06-28 through 2019-07-27.

leetcodeeasydatabase
LeetCode 36 - Valid Sudoku

This problem asks us to validate whether a partially filled Sudoku board follows the core Sudoku rules. The board is always a fixed 9 x 9 grid, and each cell contains either a digit from '1' to '9' or the character '.', which represents an empty cell.

leetcodemediumarrayhash-tablematrix
LeetCode 1342 - Number of Steps to Reduce a Number to Zero

The problem gives us a non-negative integer num and asks us to compute how many operations are required to reduce it all the way down to 0.

leetcodeeasymathbit-manipulation
LeetCode 766 - Toeplitz Matrix

The problem asks us to determine whether a given matrix satisfies the Toeplitz property. A matrix is considered Toeplitz if every diagonal running from the top-left corner toward the bottom-right corner contains identical values.

leetcodeeasyarraymatrix
LeetCode 1527 - Patients With a Condition

The problem asks us to query a database table Patients and return the records of patients who have Type I Diabetes. Each

leetcodeeasydatabase
LeetCode 1401 - Circle and Rectangle Overlapping

The problem gives two geometric shapes: 1. A circle, defined by: - radius - center coordinates (xCenter, yCenter) 2. An axis-aligned rectangle, defined by: - bottom-left corner (x1, y1) - top-right corner (x2, y2) The goal is to determine whether the circle and rectangle overlap.

leetcodemediummathgeometry
CF 120E - Put Knight!

We are asked to analyze a two-player game on an n × n chessboard. Petya and Gena take turns placing knights such that no knight can threaten another. A knight threatens positions in its standard L-shaped moves.

codeforcescompetitive-programminggamesmath
LeetCode 1368 - Minimum Cost to Make at Least One Valid Path in a Grid

This problem gives us a two dimensional grid where every cell contains a directional sign. The sign tells us which neigh

leetcodehardarraybreadth-first-searchgraph-theoryheap-(priority-queue)matrixshortest-path
LeetCode 2092 - Find All People With Secret

The problem describes a network of people who meet at different times. Whenever a person who already knows a secret participates in a meeting, they immediately share the secret with the other participant. The key detail is that sharing is instantaneous within the same timestamp.

leetcodeharddepth-first-searchbreadth-first-searchunion-findgraph-theorysorting
LeetCode 1691 - Maximum Height by Stacking Cuboids

This problem gives us a collection of 3D cuboids, where each cuboid is represented by three dimensions: width, length, a

leetcodehardarraydynamic-programmingsorting
LeetCode 1386 - Cinema Seat Allocation

Here is a complete, detailed technical solution guide for LeetCode 1386 - Cinema Seat Allocation in a single, comprehens

leetcodemediumarrayhash-tablegreedybit-manipulation
CF 123B - Squares

We move on an infinite grid of unit squares. From any square we may move one step up, down, left, or right. Some squares are marked as bad, and entering such a square costs one.

codeforcescompetitive-programmingmath
LeetCode 159 - Longest Substring with At Most Two Distinct Characters

The problem asks us to find the length of the longest contiguous substring in a string s that contains at most two distinct characters. A substring is a continuous sequence of characters inside the original string.

leetcodemediumhash-tablestringsliding-window
CF 44F - BerPaint

We have a rectangular canvas of size W × H. Initially the whole canvas is white. Then several black line segments are drawn on it. After that, a sequence of flood-fill operations is applied. A flood-fill chooses a point and a color.

codeforcescompetitive-programminggeometrygraphs
CF 11A - Increasing Sequence

We have an array of integers, and we want every element to become strictly larger than the one before it. The only operation allowed is choosing a single element and increasing it by exactly d. Every use of this operation counts as one move.

codeforcescompetitive-programmingconstructive-algorithmsimplementationmath
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
CF 18A - Triangle

We are given three points on the plane with integer coordinates. These three points already form a valid triangle, meaning they are not collinear.

codeforcescompetitive-programmingbrute-forcegeometry
LeetCode 1132 - Reported Posts II

The problem asks us to calculate the average daily percentage of posts that were removed after being reported as spam. We are given two tables: Actions and Removals.

leetcodemediumdatabase
LeetCode 1730 - Shortest Path to Get Food

The problem asks us to find the shortest path from a starting location to any food cell in a 2D grid. The grid consists of four types of cells: '' indicating your starting position, '' representing food, 'O' as free space you can move through, and 'X' as obstacles you cannot…

leetcodemediumarraybreadth-first-searchmatrix
CF 137C - History

Each historical event is represented by a time interval [a, b], where a is the starting year and b is the ending year. One event is considered contained inside another if it starts later and ends earlier.

codeforcescompetitive-programmingsortings
LeetCode 2015 - Average Height of Buildings in Each Segment

The problem describes a street as a number line, and each building occupies a half-closed interval [start, end) with a fixed height.

leetcodemediumarraysortingheap-(priority-queue)prefix-sum
LeetCode 1287 - Element Appearing More Than 25% In Sorted Array

The problem gives us a sorted integer array in non-decreasing order. We are guaranteed that exactly one element appears

leetcodeeasyarray
LeetCode 163 - Missing Ranges

This problem gives us three inputs: - A sorted array nums - A lower bound lower - An upper bound upper The array contains unique integers, and every number in the array lies within the inclusive range [lower, upper].

leetcodeeasyarray
LeetCode 1595 - Minimum Cost to Connect Two Groups of Points

The problem is asking us to find the minimum cost to connect two groups of points, where the first group has size1 point

leetcodehardarraydynamic-programmingbit-manipulationmatrixbitmask
LeetCode 633 - Sum of Square Numbers

The problem gives a non-negative integer c and asks whether it can be represented as the sum of the squares of two integers.

leetcodemediummathtwo-pointersbinary-search
LeetCode 1000 - Minimum Cost to Merge Stones

The problem asks us to merge n piles of stones into a single pile under a very specific merging rule. Each pile is represented as an integer in the array stones, where stones[i] is the number of stones in the i-th pile.

leetcodehardarraydynamic-programmingprefix-sum
LeetCode 706 - Design HashMap

The problem requires us to implement a HashMap from scratch without using any built-in hash table libraries. In other words, we need to create a data structure that can store key-value pairs, allow efficient insertion, retrieval, and deletion of values based on their keys.

leetcodeeasyarrayhash-tablelinked-listdesignhash-function
LeetCode 225 - Implement Stack using Queues

The problem asks us to implement a stack data structure while using only queue operations internally. A stack follows the Last-In-First-Out, or LIFO, principle. This means the most recently inserted element must be removed first.

leetcodeeasystackdesignqueue
LeetCode 793 - Preimage Size of Factorial Zeroes Function

This problem asks us to determine how many non-negative integers x exist such that the factorial of x ends with exactly k trailing zeroes. The function f(x) counts trailing zeroes in x!. For example, f(3) = 0 because 3! = 6 has no trailing zeroes, and f(11) = 2 because 11!

leetcodehardmathbinary-search
LeetCode 1176 - Diet Plan Performance

The problem is asking us to simulate a dieter’s performance over a sequence of days based on their calorie consumption. The input is an array calories where calories[i] represents the number of calories consumed on day i. We are also given three integers: k, lower, and upper.

leetcodeeasyarraysliding-window
LeetCode 1602 - Find Nearest Right Node in Binary Tree

This problem asks us to find the nearest node to the right of a given node u on the same level of a binary tree. A binar

leetcodemediumtreebreadth-first-searchbinary-tree
LeetCode 235 - Lowest Common Ancestor of a Binary Search Tree

The problem asks us to find the Lowest Common Ancestor, commonly abbreviated as LCA, of two nodes in a Binary Search Tree (BST). A lowest common ancestor of two nodes p and q is the deepest node in the tree that has both p and q as descendants.

leetcodemediumtreedepth-first-searchbinary-search-treebinary-tree
LeetCode 2016 - Maximum Difference Between Increasing Elements

The problem is asking us to find the maximum difference between two elements in an array, with the condition that the smaller element appears before the larger element.

leetcodeeasyarray
LeetCode 885 - Spiral Matrix III

The problem is asking us to generate the coordinates of cells in a 2D grid that we would visit if we started at a given cell (rStart, cStart) and walked in a clockwise spiral pattern.

leetcodemediumarraymatrixsimulation
CF 107B - Basketball Team

We have a university with several departments. Each department contributes some number of basketball players. Herr Wafa belongs to department h, and he is already guaranteed a place on the final team. The team must contain exactly n players including Wafa himself.

codeforcescompetitive-programmingcombinatoricsdpmathprobabilities
CF 34E - Collisions

We have several point-like balls moving on a one-dimensional line. Every ball starts at some coordinate with its own velocity and mass.

codeforcescompetitive-programmingbrute-forceimplementationmath
CF 120B - Quiz League

We are given a circular table divided into n sectors, each containing a quiz question. Some questions have already been asked, marked with a 0, and others are still available, marked with a 1.

codeforcescompetitive-programmingimplementation
CF 34B - Sale

Bob is at a sale with a collection of old TVs, each with a price. Some TVs are free, some have positive prices, and some even have negative prices, which means the owner is willing to pay Bob to take them away.

codeforcescompetitive-programminggreedysortings
LeetCode 29 - Divide Two Integers

The problem asks us to implement integer division without using the standard arithmetic operators for multiplication, division, or modulo. We are given two integers, dividend and divisor, and we must compute the quotient obtained by dividing the dividend by the divisor.

leetcodemediummathbit-manipulation
CF 29D - Ant on the Tree

We are asked to construct a path for an ant on a tree. The tree has n vertices, with vertex 1 as the root, and n-1 edges connecting them so the graph is connected.

codeforcescompetitive-programmingconstructive-algorithmsdfs-and-similartrees
CF 78D - Archer's Shot

We are asked to calculate how many hexagonal cells a single archer can fully cover with a circular attack of radius k, where the archer is positioned at the center of a cell. Each hexagon has side length 1.

codeforcescompetitive-programmingbinary-searchgeometrymathtwo-pointers
LeetCode 1374 - Generate a String With Characters That Have Odd Counts

The problem asks us to generate a string of length n such that each character in the string occurs an odd number of time

leetcodeeasystring
LeetCode 1252 - Cells with Odd Values in a Matrix

The problem gives us an m x n matrix where every cell initially contains 0. We are also given a list called indices, whe

leetcodeeasyarraymathsimulation
LeetCode 1754 - Largest Merge Of Two Strings

This problem asks us to build the lexicographically largest possible string by repeatedly choosing characters from the front of two given strings.

leetcodemediumtwo-pointersstringgreedy
LeetCode 1057 - Campus Bikes

This problem models a matching process between workers and bikes on a two dimensional grid. Each worker and each bike has a unique coordinate, and every worker must eventually receive exactly one bike.

leetcodemediumarraysortingheap-(priority-queue)
LeetCode 1364 - Number of Trusted Contacts of a Customer

This problem asks us to analyze relationships between customers, their contacts, and invoices. We are given three tables: Customers, Contacts, and Invoices. The Customers table identifies each customer by customerid along with their name and email.

leetcodemediumdatabase
LeetCode 214 - Shortest Palindrome

The problem gives a string s and asks us to create the shortest possible palindrome by adding characters only at the beginning of the string. A palindrome is a string that reads the same forward and backward.

leetcodehardstringrolling-hashstring-matchinghash-function
LeetCode 1736 - Latest Time by Replacing Hidden Digits

The problem presents a string time formatted as hh:mm, where h and m are digits representing hours and minutes, respectively. Some digits may be hidden and are represented by a question mark ?. The goal is to replace the ?

leetcodeeasystringgreedy
LeetCode 2123 - Minimum Operations to Remove Adjacent Ones in Matrix

The problem presents a binary matrix where each element is either 0 or 1. The goal is to transform this matrix into a well-isolated configuration, meaning that no 1 is 4-directionally connected to any other 1.

leetcodehardarraygraph-theorymatrix
LeetCode 40 - Combination Sum II

This problem asks us to find all unique combinations of numbers from the candidates array such that the sum of the chosen numbers equals target. Unlike the original Combination Sum problem, each number can only be used once.

leetcodemediumarraybacktracking
LeetCode 1814 - Count Nice Pairs in an Array

The problem gives us an array of non-negative integers called nums. We need to count how many index pairs (i, j) satisfy the following conditions: - i < j - nums[i] + rev(nums[j]) == nums[j] + rev(nums[i]) Here, rev(x) means reversing the digits of the integer.

leetcodemediumarrayhash-tablemathcounting
LeetCode 595 - Big Countries

This problem asks us to query a database table named World and return a subset of countries that qualify as big countries.

leetcodeeasydatabase
LeetCode 1679 - Max Number of K-Sum Pairs

The problem asks us to repeatedly remove pairs of numbers from an array such that the sum of each selected pair equals a

leetcodemediumarrayhash-tabletwo-pointerssorting
CF 58C - Trees

We are given a row of n trees, each with a certain height, and our task is to adjust some of their heights so that the row forms a “beautiful” sequence.

codeforcescompetitive-programmingbrute-force
CF 5B - Center Alignment

We are given several lines of text. Every line may contain letters, digits, and spaces inside the line, but never at the beginning or end. The task is to print all lines inside a rectangular frame made of * characters.

codeforcescompetitive-programmingimplementationstrings