brain

tamnd's digital brain — notes, problems, research

42684 notes

LeetCode 1465 - Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts

This problem gives us a rectangular cake with height h and width w. We are also given two arrays: - horizontalCuts, whic

leetcodemediumarraygreedysorting
CF 45F - Goats and Wolves

We have the classical river crossing setting, but with a precise safety rule that changes how transitions work.

codeforcescompetitive-programminggreedy
LeetCode 182 - Duplicate Emails

The problem gives us a database table named Person with two columns: Column Description --- --- id A unique integer identifier for each row email The email address associated with that row The goal is to find all email addresses that appear more than once in the table.

leetcodeeasydatabase
LeetCode 1114 - Print in Order

This problem asks us to coordinate three independent threads so that they execute in a strict order, regardless of how the operating system schedules them. We are given a class with three methods, first(), second(), and third().

leetcodeeasyconcurrency
LeetCode 755 - Pour Water

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

leetcodemediumarraysimulation
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
CF 12E - Start of the session

We are asked to construct a square matrix of size _n_ × _n_, where _n_ is an even number. The matrix must satisfy four properties. The main diagonal contains only zeroes.

codeforcescompetitive-programmingconstructive-algorithms
LeetCode 129 - Sum Root to Leaf Numbers

The problem gives us the root of a binary tree where every node contains a single digit from 0 to 9. Every path starting from the root and ending at a leaf node forms a number by concatenating the digits along that path.

leetcodemediumtreedepth-first-searchbinary-tree
LeetCode 1788 - Maximize the Beauty of the Garden

We are given an integer array flowers, where each element represents the beauty value of a flower in a line. We may remove any flowers we want, while preserving the relative order of the remaining flowers. After removals, the remaining sequence must form a valid garden.

leetcodehardarrayhash-tablegreedyprefix-sum
CF 73D - FreeDiv

We are given an undirected graph where cities are vertices and roads are edges. Each connected component of the graph is called a province. Vasya may additionally build tunnels between cities, but tunnels have two restrictions.

codeforcescompetitive-programmingdfs-and-similargraphsgreedy
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 1739 - Building Boxes

The problem gives us n identical unit cubes that must be placed inside a cubic room. The goal is to minimize how many boxes directly touch the floor. The placement rule is the important part of the problem.

leetcodehardmathbinary-searchgreedy
LeetCode 1143 - Longest Common Subsequence

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

leetcodemediumstringdynamic-programming
CF 85A - Domino

We need to tile a 4 × n board using ordinary dominoes. Each domino covers exactly two neighboring cells, either horizontally or vertically. The tiling must satisfy an extra condition.

codeforcescompetitive-programmingconstructive-algorithmsimplementation
LeetCode 142 - Linked List Cycle II

This problem asks us to determine whether a singly linked list contains a cycle and, if it does, return the exact node where that cycle begins. A linked list is normally a sequence of nodes where each node points to the next one, eventually ending with null.

leetcodemediumhash-tablelinked-listtwo-pointers
CF 66E - Petya and Post

We have a circular route with n post offices, each with a gas station. Each station i has a[i] liters of gasoline available, and the distance from station i to i+1 is b[i] kilometers, wrapping around at the end.

codeforcescompetitive-programmingdata-structuresdp
LeetCode 1593 - Split a String Into the Max Number of Unique Substrings

This problem asks us to split a string into the largest possible number of substrings such that every substring is uniqu

leetcodemediumhash-tablestringbacktracking
LeetCode 116 - Populating Next Right Pointers in Each Node

This problem asks us to populate the next pointers of nodes in a perfect binary tree. A perfect binary tree has all levels completely filled; every internal node has exactly two children, and all leaves are at the same depth.

leetcodemediumlinked-listtreedepth-first-searchbreadth-first-searchbinary-tree
CF 25B - Phone numbers

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

codeforcescompetitive-programmingimplementation
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 448 - Find All Numbers Disappeared in an Array

The problem asks us to find all the integers in the range [1, n] that are missing from an input array nums of length n.

leetcodeeasyarrayhash-table
LeetCode 482 - License Key Formatting

The problem gives us a string s that represents a license key. The string contains uppercase letters, lowercase letters, digits, and dashes. The existing dashes are only separators and do not necessarily represent the correct final grouping.

leetcodeeasystring
LeetCode 1026 - Maximum Difference Between Node and Ancestor

This problem asks us to find the largest absolute difference between the values of two nodes in a binary tree, under one important condition: one node must be an ancestor of the other.

leetcodemediumtreedepth-first-searchbinary-tree
LeetCode 106 - Construct Binary Tree from Inorder and Postorder Traversal

The problem provides two traversal orders of the same binary tree: - inorder, which follows the order: left subtree, root, right subtree - postorder, which follows the order: left subtree, right subtree, root We must reconstruct the original binary tree and return its root node.

leetcodemediumarrayhash-tabledivide-and-conquertreebinary-tree
LeetCode 366 - Find Leaves of Binary Tree

The problem asks us to repeatedly remove all leaf nodes from a binary tree and record the values removed during each round. A leaf node is a node with no left or right child.

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

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

codeforcescompetitive-programmingdpgamesstrings
LeetCode 1712 - Ways to Split Array Into Three Subarrays

The problem asks us to count the number of valid ways to divide an array into three contiguous, non-empty parts: - left - mid - right The split must satisfy two conditions: 1. sum(left) <= sum(mid) 2.

leetcodemediumarraytwo-pointersbinary-searchprefix-sum
LeetCode 355 - Design Twitter

This problem asks us to design a simplified version of a social media platform similar to Twitter. The system must support four main operations: 1. Users can post tweets. 2. Users can follow other users. 3. Users can unfollow other users. 4.

leetcodemediumhash-tablelinked-listdesignheap-(priority-queue)
CF 14E - Camels

We are counting sequences of heights that describe a polyline. The x-coordinates are fixed as 1, 2, ..., n, so the whole shape is determined only by the sequence y1, y2, ..., yn.

codeforcescompetitive-programmingdp
LeetCode 1275 - Find Winner on a Tic Tac Toe Game

This problem asks us to simulate a game of Tic-Tac-Toe on a 3 x 3 grid given a sequence of moves. Each move specifies th

leetcodeeasyarrayhash-tablematrixsimulation
LeetCode 1463 - Cherry Pickup II

Here is a complete, detailed technical solution guide for LeetCode 1463 - Cherry Pickup II following your formatting req

leetcodehardarraydynamic-programmingmatrix
LeetCode 694 - Number of Distinct Islands

The problem gives us a binary matrix called grid, where each cell contains either 0 or 1. A value of 1 represents land, and a value of 0 represents water. An island is formed by connecting adjacent land cells in the four cardinal directions: up, down, left, and right.

leetcodemediumarrayhash-tabledepth-first-searchbreadth-first-searchunion-findsortingmatrixhash-function
CF 36A - Extra-terrestrial Intelligence

We are given a binary string representing Vasya's observations over several days. A character '1' means a signal was received on that day, while '0' means no signal appeared.

codeforcescompetitive-programmingimplementation
LeetCode 817 - Linked List Components

The problem gives us a singly linked list where every node contains a unique integer value. We are also given an array nums, and every value in nums is guaranteed to appear somewhere in the linked list.

leetcodemediumarrayhash-tablelinked-list
LeetCode 283 - Move Zeroes

The problem gives us an integer array nums and asks us to move every 0 element to the end of the array while preserving the relative order of all non-zero elements. The phrase "relative order" is extremely important.

leetcodeeasyarraytwo-pointers
CF 6C - Alice, Bob and Chocolate

We have a row of chocolate bars, and each bar takes a certain amount of time to eat. Alice starts from the left end and keeps moving right. Bob starts from the right end and keeps moving left.

codeforcescompetitive-programminggreedytwo-pointers
CF 130J - Date calculation

We are given a year in the Gregorian calendar and a day number inside that year. The task is to determine the actual calendar date corresponding to that day number.

codeforcescompetitive-programming*special
LeetCode 502 - IPO

The problem describes a scenario where we have a limited number of opportunities to invest in projects before an IPO.

leetcodehardarraygreedysortingheap-(priority-queue)
LeetCode 3054 - Binary Tree Nodes

This problem asks us to classify nodes in a binary tree based on their role in the tree structure. The input is represen

leetcodemediumdatabase
LeetCode 290 - Word Pattern

The problem gives two inputs: a pattern string and a space-separated string of words. We need to determine whether the sequence of words follows the same structure as the sequence of characters in the pattern.

leetcodeeasyhash-tablestring
LeetCode 394 - Decode String

The problem gives us a string that contains encoded patterns of the form k[encodedstring]. The integer k tells us how many times the substring inside the brackets should be repeated. Our task is to fully decode the string and return the expanded result.

leetcodemediumstringstackrecursion
LeetCode 1584 - Min Cost to Connect All Points

This problem asks us to connect all given points on a 2D plane with the minimum possible total cost. Each point is repre

leetcodemediumarrayunion-findgraph-theoryminimum-spanning-tree
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 979 - Distribute Coins in Binary Tree

In this problem, we are given a binary tree where every node contains some number of coins. The total number of coins across the entire tree is exactly equal to the number of nodes in the tree.

leetcodemediumtreedepth-first-searchbinary-tree
LeetCode 222 - Count Complete Tree Nodes

The problem asks us to count how many nodes exist in a complete binary tree. A complete binary tree has a very specific structure. Every level except possibly the last one is completely filled, and the nodes on the final level appear as far left as possible.

leetcodeeasybinary-searchbit-manipulationtreebinary-tree
LeetCode 1006 - Clumsy Factorial

The problem asks us to compute a clumsy factorial for a given positive integer n. A standard factorial multiplies all integers from n down to 1, but the clumsy factorial modifies the operations: instead of multiplying all numbers, it cycles through '', '/', '+', and '-' in…

leetcodemediummathstacksimulation
CF 70E - Information Reform

We are given a country with cities connected by roads such that the road network forms a tree: there is exactly one simple path between any two cities. Each road has equal length in terms of counting the number of edges.

codeforcescompetitive-programmingdpimplementationtrees
CF 53A - Autocomplete

We are asked to implement a simplified autocomplete function. The input consists of a string s, which represents the text the user has typed so far, followed by a list of previously visited pages.

codeforcescompetitive-programmingimplementation
CF 75D - Big Maximum Sum

We are given a set of small arrays and a sequence of indexes indicating how to concatenate them into one larger array. Once the large array is built in this way, the goal is to find the maximum sum of a contiguous subarray.

codeforcescompetitive-programmingdata-structuresdpgreedyimplementationmathtrees
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 69E - Subsegments

We are given an array of integers and a fixed window size k. For each contiguous subarray (segment) of length k, we need to find the largest element that appears exactly once within that segment. If no element appears exactly once, we output "Nothing".

codeforcescompetitive-programmingdata-structuresimplementation
CF 82D - Two out of Three

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

codeforcescompetitive-programmingdp
LeetCode 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
CF 97E - Leaders

We are given an undirected graph where vertices represent people and edges represent relationships. For every query (u, v), we must decide whether there exists a simple path from u to v whose length is odd. The keyword here is "simple". We are not allowed to revisit vertices.

codeforcescompetitive-programmingdfs-and-similardsugraphstrees
CF 52A - 123-sequence

We are given a list of integers where every number is either 1, 2, or 3. The goal is to transform the sequence so that all numbers are the same, and we want to do this using the smallest number of replacements possible.

codeforcescompetitive-programmingimplementation
LeetCode 1662 - Check If Two String Arrays are Equivalent

The problem gives us two arrays of strings, word1 and word2. Each array represents a single larger string formed by conc

leetcodeeasyarraystring
LeetCode 333 - Largest BST Subtree

The problem gives us the root of an arbitrary binary tree and asks us to find the size of the largest subtree that is also a valid Binary Search Tree, abbreviated as BST. A subtree is any node together with all of its descendants. This means we cannot selectively ignore children.

leetcodemediumdynamic-programmingtreedepth-first-searchbinary-search-treebinary-tree
LeetCode 73 - Set Matrix Zeroes

The problem gives us a two dimensional matrix of integers with m rows and n columns. We must modify the matrix in place so that whenever a cell contains 0, every element in that cell's entire row and entire column also becomes 0.

leetcodemediumarrayhash-tablematrix
LeetCode 1030 - Matrix Cells in Distance Order

This problem asks us to return every cell in a matrix, ordered by its Manhattan distance from a given center cell.

leetcodeeasyarraymathgeometrysortingmatrix
LeetCode 475 - Heaters

The problem gives two arrays, houses and heaters, where each value represents a position on a one dimensional horizontal line.

leetcodemediumarraytwo-pointersbinary-searchsorting
LeetCode 41 - First Missing Positive

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

leetcodehardarrayhash-table
CF 8D - Two Friends

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

codeforcescompetitive-programmingbinary-searchgeometry
CF 24C - Sequence of points

We are given a sequence of points on the 2D integer grid: a starting point M0 and a sequence of n points A0, A1, …, An-1, where n is always odd. We then define a new sequence M1, M2, … where each Mi is the reflection of Mi-1 over one of the Ai points.

codeforcescompetitive-programminggeometryimplementationmath
CF 78A - Haiku

We are given three lines representing the three phrases of a poem. A valid haiku must contain exactly 5 vowel letters in the first phrase, 7 in the second, and 5 in the third. For this problem, syllables are simplified into vowel counts.

codeforcescompetitive-programmingimplementationstrings
LeetCode 1067 - Digit Count in Range

This problem asks us to count how many times a given digit d appears in every integer within a range [low, high]. For instance, if d = 1 and the range is [1, 13], we count all occurrences of the digit 1 in the numbers 1 through 13.

leetcodehardmathdynamic-programming
LeetCode 1350 - Students With Invalid Departments

This problem asks us to identify students who are enrolled in university departments that no longer exist in the departm

leetcodeeasydatabase
LeetCode 1772 - Sort Features by Popularity

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

leetcodemediumarrayhash-tablestringsorting
LeetCode 806 - Number of Lines To Write String

This problem is asking us to determine how to write a string s on multiple lines when each character has a specific pixel width and no line can exceed 100 pixels.

leetcodeeasyarraystring
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 1187 - Make Array Strictly Increasing

The problem is asking us to transform the array arr1 into a strictly increasing array using the minimum number of operations. Each operation allows replacing an element of arr1 with an element from arr2.

leetcodehardarraybinary-searchdynamic-programmingsorting
CF 113D - Museum

We are asked to model the random movements of two friends inside a museum represented as an undirected connected graph with n rooms and m corridors. Each room has a probability of staying in place for a minute, and otherwise the person moves uniformly to a neighboring room.

codeforcescompetitive-programmingmathmatricesprobabilities
LeetCode 954 - Array of Doubled Pairs

The problem asks whether it is possible to reorder an even-length array arr of integers such that every element can be paired with another element that is exactly double its value.

leetcodemediumarrayhash-tablegreedysorting
LeetCode 47 - Permutations II

The problem asks us to generate every possible permutation of the given array nums, while ensuring that duplicate permutations are not included in the final result. A permutation is an arrangement of all elements in a particular order.

leetcodemediumarraybacktrackingsorting
LeetCode 212 - Word Search II

LeetCode 212, LeetCode Word Search II, asks us to find every word from a given dictionary that can be formed inside a 2D character grid. Each word must be built by moving one cell at a time horizontally or vertically.

leetcodehardarraystringbacktrackingtriematrix
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
LeetCode 1266 - Minimum Time Visiting All Points

The problem gives a sequence of points on a 2D coordinate plane. Each point is represented as [x, y], where x and y are

leetcodeeasyarraymathgeometry
LeetCode 1650 - Lowest Common Ancestor of a Binary Tree III

This problem asks us to find the lowest common ancestor, usually abbreviated as LCA, of two nodes in a binary tree. Unli

leetcodemediumhash-tabletwo-pointerstreebinary-tree
LeetCode 1752 - Check if Array Is Sorted and Rotated

The problem is asking us to determine whether a given array nums could be the result of taking a sorted array in non-decreasing order and then rotating it by some number of positions. A non-decreasing array is one where each element is greater than or equal to the previous one.

leetcodeeasyarray
LeetCode 1652 - Defuse the Bomb

The problem gives us a circular array called code and an integer k. We must produce a new array where each element is replaced according to the value of k. If k 0, each element becomes the sum of the next k elements in the circular array.

leetcodeeasyarraysliding-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 37C - Old Berland Language

We need to construct a binary prefix code.

codeforcescompetitive-programmingdata-structuresgreedytrees
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
CF 29A - Spit Problem

Each camel stands at a unique coordinate on a number line. A camel at position x spits exactly toward position x + d. If another camel stands there, it gets hit. We need to determine whether there exists a pair of camels such that each one hits the other.

codeforcescompetitive-programmingbrute-force
CF 1941F - Rudolf and Imbalance

We start with a strictly increasing array of problem complexities. The imbalance of the set is defined as the largest difference between two neighboring elements after sorting.

codeforcescompetitive-programmingbinary-searchgreedysortingstwo-pointers
CF 39B - Company Income Growth

We are given a sequence of integers representing the yearly income of a company starting from 2001. The first number is the income in 2001, the second in 2002, and so on. These values may be negative if the company incurred a loss that year.

codeforcescompetitive-programminggreedy
LeetCode 413 - Arithmetic Slices

The problem asks us to count how many contiguous subarrays of length at least three form an arithmetic sequence. An arithmetic sequence is one where the difference between every pair of adjacent elements is identical.

leetcodemediumarraydynamic-programmingsliding-window
LeetCode 1713 - Minimum Operations to Make a Subsequence

The problem gives us two arrays, target and arr. The target array contains distinct integers, which is extremely important. The arr array may contain duplicates. We are allowed to perform insert operations on arr.

leetcodehardarrayhash-tablebinary-searchgreedy
LeetCode 292 - Nim Game

The problem describes a two-player game involving a single heap of stones. There are n stones initially on the table, and players alternate turns removing stones. On each turn, a player may remove either 1, 2, or 3 stones. The player who removes the final stone wins the game.

leetcodeeasymathbrainteasergame-theory
LeetCode 1567 - Maximum Length of Subarray With Positive Product

The problem asks us to find the length of the longest contiguous subarray whose product of elements is strictly positive. We are given an integer array nums, which may contain positive numbers, negative numbers, and zeros.

leetcodemediumarraydynamic-programminggreedy
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
LeetCode 1281 - Subtract the Product and Sum of Digits of an Integer

The problem asks us to compute a simple mathematical transformation on the digits of an integer. Given an integer n, we

leetcodeeasymath
CF 116B - Little Pigs and Wolves

We have a small rectangular grid where each cell is either empty, contains a pig, or contains a wolf. A wolf may eat one pig that is directly adjacent to it in one of the four cardinal directions. Once a pig is eaten, it disappears and cannot be eaten again.

codeforcescompetitive-programminggreedyimplementation
CF 33B - String Problem

We are given two lowercase strings of the same length. We may repeatedly transform characters using directed conversion rules. A rule like a -> b with cost 5 means we can change one occurrence of a into b by paying 5.

codeforcescompetitive-programmingshortest-paths
LeetCode 1660 - Correct a Binary Tree

Here is a complete, detailed technical solution guide for LeetCode 1660 - Correct a Binary Tree, formatted exactly as re

leetcodemediumhash-tabletreedepth-first-searchbreadth-first-searchbinary-tree
LeetCode 1769 - Minimum Number of Operations to Move All Balls to Each Box

This problem asks us to compute the minimum number of moves required to gather all balls in a string of boxes into each individual box. Each box can either be empty ('0') or contain one ball ('1'). A single operation consists of moving a ball from one box to an adjacent box.

leetcodemediumarraystringprefix-sum
LeetCode 489 - Robot Room Cleaner

This problem is an interactive backtracking problem where we must control a robot without directly seeing the room layout. Unlike traditional grid traversal problems, we are not given access to the actual room matrix during execution.

leetcodehardbacktrackinginteractive
LeetCode 1398 - Customers Who Bought Products A and B but Not C

The problem asks us to identify customers who meet a very specific purchasing pattern. We are given two tables: Customer

leetcodemediumdatabase
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
LeetCode 1383 - Maximum Performance of a Team

This problem asks us to build a team of at most k engineers such that the team's performance is maximized. Each engineer

leetcodehardarraygreedysortingheap-(priority-queue)
CF 18E - Flag 2

We are given a flag represented as an _n_×_m_ grid where each cell is painted with one of 26 colours labeled a to z. The goal is to repaint as few squares as possible so that two conditions hold. First, each row can use at most two different colours.

codeforcescompetitive-programmingdp