brain

tamnd's digital brain — notes, problems, research

42656 notes

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
CF 64C - Table

We are given an $n times m$ table filled with consecutive integers starting from 1. The filling is done row by row, left to right.

codeforcescompetitive-programming*specialgreedyimplementationmath
LeetCode 1166 - Design File System

This problem asks us to design a simplified file system that supports two operations: 1. Creating a new path with an associated integer value. 2. Retrieving the value stored at a path. A path behaves similarly to a directory structure in a real operating system.

leetcodemediumhash-tablestringdesigntrie
LeetCode 1179 - Reformat Department Table

The problem is asking us to take a table Department that records revenue per department per month in a vertical format and convert it into a horizontal format, often called a "pivot" table. In the input, each row contains a department id, a revenue value, and a month.

leetcodeeasydatabase
LeetCode 150 - Evaluate Reverse Polish Notation

This problem asks us to evaluate an arithmetic expression written in Reverse Polish Notation, also called postfix notation. Instead of placing operators between operands as in standard infix notation, Reverse Polish Notation places operators after their operands.

leetcodemediumarraymathstack
CF 47C - Crossword

We are given six words and must arrange them into a very specific crossword shape. The shape looks like a rectangular infinity symbol. There are three horizontal words and three vertical words, and they intersect at fixed positions.

codeforcescompetitive-programmingimplementation
LeetCode 2005 - Subtree Removal Game with Fibonacci Tree

The problem defines a special kind of binary tree called a Fibonacci tree. The structure is recursive: - order(0) is an empty tree. - order(1) is a single node. - order(n) has: - a root node, - a left subtree equal to order(n - 2), - a right subtree equal to order(n - 1).

leetcodehardmathdynamic-programmingtreebinary-treegame-theory
LeetCode 1094 - Car Pooling

This problem asks us to determine whether a car can successfully complete a series of passenger trips without ever exceeding its seating capacity.

leetcodemediumarraysortingheap-(priority-queue)simulationprefix-sum
LeetCode 1562 - Find Latest Group of Size M

Edit This problem gives us a permutation array arr containing integers from 1 to n, where n is the size of the binary st

leetcodemediumarrayhash-tablebinary-searchsimulation
CF 72A - Goshtasp, Vishtasp and Eidi

The problem asks us to decide whether a positive integer $n$ can be represented as a sum of distinct integers, where each integer is either 1 or a prime number. If such a representation exists, we need to produce one that is lexicographically largest.

codeforcescompetitive-programming*specialgreedymath
LeetCode 1062 - Longest Repeating Substring

The problem asks us to find the length of the longest substring that appears at least twice in a given string s. A substring is a contiguous sequence of characters inside a string. The repeated substrings may overlap with each other, which is an important detail.

leetcodemediumstringbinary-searchdynamic-programmingrolling-hashsuffix-arrayhash-function
CF 48H - Black and White

We are asked to tile an rectangular floor with three types of 2x2 square tiles: black, white, and mixed tiles that have a black and a white section in a diagonal pattern.

codeforcescompetitive-programmingconstructive-algorithms
CF 111B - Petya and Divisors

We are asked to process a sequence of queries, each defined by two integers, x and y. For each query, we need to count how many positive divisors of x do not divide any of the y numbers immediately preceding x in the sequence, that is, the numbers x-y, x-y+1, ..., x-1.

codeforcescompetitive-programmingbinary-searchdata-structuresnumber-theory
LeetCode 118 - Pascal's Triangle

The problem is asking us to generate the first numRows of Pascal's triangle, which is a triangular arrangement of numbers where each number is the sum of the two numbers directly above it.

leetcodeeasyarraydynamic-programming
LeetCode 1069 - Product Sales Analysis II

This problem asks us to calculate the total quantity sold for each product based on records in the Sales table. The Sales table contains transaction level information.

leetcodeeasydatabase
LeetCode 1085 - Sum of Digits in the Minimum Number

This problem asks us to examine the smallest number in the input array and determine whether the sum of its digits is odd or even. We are given an integer array nums. The task consists of three clear steps: 1. Find the minimum integer in the array. 2.

leetcodeeasyarraymath
LeetCode 1232 - Check If It Is a Straight Line

The problem asks us to determine whether a given set of points in a 2D Cartesian plane all lie on a single straight line. The input is a list of integer coordinates, where each coordinate [x, y] represents a point.

leetcodeeasyarraymathgeometry
LeetCode 602 - Friend Requests II: Who Has the Most Friends

The problem gives us a database table named RequestAccepted, where each row represents a successfully accepted friend request between two users. Every record contains a requesterid, an accepterid, and the date the request was accepted.

leetcodemediumdatabase
LeetCode 1518 - Water Bottles

The problem is asking us to determine the maximum number of water bottles a person can drink given two integers: numBott

leetcodeeasymathsimulation
LeetCode 474 - Ones and Zeroes

This problem asks us to select the largest possible subset of binary strings while staying within two resource constraints. Each string consumes a certain number of 0 characters and a certain number of 1 characters.

leetcodemediumarraystringdynamic-programming
LeetCode 610 - Triangle Judgement

The problem is asking us to determine, for each row in a table called Triangle, whether the three given line segments can form a valid triangle. Each row contains three integers x, y, and z representing the lengths of the segments.

leetcodeeasydatabase
LeetCode 162 - Find Peak Element

The problem gives us an integer array nums and asks us to find the index of any peak element. A peak element is defined as an element that is strictly greater than its immediate neighbors.

leetcodemediumarraybinary-search
LeetCode 1271 - Hexspeak

The problem asks us to convert a decimal number given as a string into its Hexspeak representation. Hexspeak is derived

leetcodeeasymathstring
LeetCode 248 - Strobogrammatic Number III

The problem asks us to count how many numbers within the inclusive range [low, high] are strobogrammatic. A strobogrammatic number is a number that appears unchanged when rotated 180 degrees.

leetcodehardarraystringrecursion
LeetCode 33 - Search in Rotated Sorted Array

The problem gives us an array that was originally sorted in ascending order, but may have been rotated at some pivot point. A rotation means that some prefix of the sorted array was moved to the end while preserving the relative order of elements.

leetcodemediumarraybinary-search
LeetCode 1262 - Greatest Sum Divisible by Three

The problem asks us to find the maximum sum of elements from an integer array nums such that the sum is divisible by thr

leetcodemediumarraydynamic-programminggreedysorting
CF 22E - Scheme

Each person points to exactly one other person. If someone learns the news, they call the person they point to, who then calls the next person, and so on. We may add extra directed edges of the form x -> y, meaning person x must also call y.

codeforcescompetitive-programmingdfs-and-similargraphstrees
LeetCode 32 - Longest Valid Parentheses

The problem asks us to find the length of the longest contiguous substring that forms a valid parentheses sequence. A valid parentheses sequence is one where every opening parenthesis '(' has a corresponding closing parenthesis ')', and the pairs are correctly nested.

leetcodehardstringdynamic-programmingstack
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 45 - Jump Game II

The problem gives an array nums where each value represents the maximum distance you can jump forward from that position. You start at index 0, and your goal is to reach the final index using the minimum number of jumps possible.

leetcodemediumarraydynamic-programminggreedy
CF 65E - Harry Potter and Moving Staircases

We are given an undirected multigraph. Floors are vertices, staircases are edges. Harry starts at floor 1 and wants to visit every floor at least once. The graph is dynamic. Between Harry's walks, Ron and Hermione may modify staircases.

codeforcescompetitive-programmingdfs-and-similarimplementation
LeetCode 1191 - K-Concatenation Maximum Sum

This problem asks us to find the maximum possible sum of a contiguous subarray when we are allowed to delete at most one element from that chosen subarray. The important detail is that the resulting subarray must still contain at least one element after deletion.

leetcodemediumarraydynamic-programming
LeetCode 1457 - Pseudo-Palindromic Paths in a Binary Tree

This problem asks us to count how many root to leaf paths in a binary tree are "pseudo-palindromic". A palindrome is a s

leetcodemediumbit-manipulationtreedepth-first-searchbreadth-first-searchbinary-tree
LeetCode 167 - Two Sum II - Input Array Is Sorted

This problem gives us a sorted, 1-indexed array of integers called numbers and a target integer target. Our task is to find exactly two numbers in the array whose sum equals target, then return their 1-based indices.

leetcodemediumarraytwo-pointersbinary-search
LeetCode 573 - Squirrel Simulation

This problem models a squirrel collecting nuts in a 2D garden grid. The garden has a fixed tree position, a starting squirrel position, and multiple nuts scattered around the grid.

leetcodemediumarraymath
LeetCode 915 - Partition Array into Disjoint Intervals

The problem asks us to split an array into two contiguous parts, left and right, such that every value in left is less than or equal to every value in right. Among all valid partitions, we must return the smallest possible size of left.

leetcodemediumarray
LeetCode 1324 - Print Words Vertically

The problem requires us to take a string s containing multiple words separated by single spaces and return a list of strings representing the words written vertically.

leetcodemediumarraystringsimulation
LeetCode 429 - N-ary Tree Level Order Traversal

The problem asks us to perform a level order traversal of an n-ary tree. In other words, we need to return the values of the tree nodes grouped by their depth. The root node represents level 0, its immediate children are level 1, their children are level 2, and so on.

leetcodemediumtreebreadth-first-search
LeetCode 821 - Shortest Distance to a Character

The problem gives us a string s and a target character c. For every index in the string, we must compute the distance to the nearest occurrence of c. The distance between two indices is defined as: where i is the current index and j is the index of some occurrence of c.

leetcodeeasyarraytwo-pointersstring
CF 16D - Logging

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

codeforcescompetitive-programmingimplementationstrings
LeetCode 1578 - Minimum Time to Make Rope Colorful

The problem requires transforming a rope of balloons into a "colorful" rope, which means no two consecutive balloons sha

leetcodemediumarraystringdynamic-programminggreedy
CF 14B - Young Photographer

The problem asks us to determine how far Bob, a photographer, must move along a straight racetrack to take pictures of every sportsman. Each sportsman runs back and forth along a fixed segment of the racetrack, defined by two positions ai and bi.

codeforcescompetitive-programmingimplementation
LeetCode 570 - Managers with at Least 5 Direct Reports

The Employee table represents a company hierarchy. Every row corresponds to one employee and contains four pieces of information: Column Meaning --- --- id Unique employee identifier name Employee name department Department the employee belongs to managerId The id of this…

leetcodemediumdatabase
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 1690 - Stone Game VII

This problem describes a two player game played on an array of stones. Each stone has a positive integer value, and the

leetcodemediumarraymathdynamic-programminggame-theory
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 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
LeetCode 1325 - Delete Leaves With a Given Value

This problem asks us to repeatedly remove leaf nodes from a binary tree if their value matches a given target. A leaf no

leetcodemediumtreedepth-first-searchbinary-tree
LeetCode 1327 - List the Products Ordered in a Period

The problem asks us to list all products that have been ordered in February 2020 with a total quantity of at least 100 u

leetcodeeasydatabase
CF 118E - Bertown roads

We are given a connected undirected graph representing the road network of Bertown, where junctions are nodes and roads are edges.

codeforcescompetitive-programmingdfs-and-similargraphs
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
LeetCode 1208 - Get Equal Substrings Within Budget

The problem asks us to determine the longest contiguous substring of s that can be transformed into the corresponding substring of t without exceeding a given budget, maxCost.

leetcodemediumstringbinary-searchsliding-windowprefix-sum
LeetCode 303 - Range Sum Query - Immutable

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

leetcodeeasyarraydesignprefix-sum
LeetCode 2028 - Find Missing Observations

The problem gives us the results of some dice rolls and asks us to reconstruct the missing ones. We have a total of n + m rolls of a standard 6-sided die.

leetcodemediumarraymathsimulation
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 2233 - Maximum Product After K Increments

The problem asks us to maximize the product of an array of non-negative integers after performing at most k increment op

leetcodemediumarraygreedyheap-(priority-queue)
CF 26D - Tickets

We have a ticket seller, Charlie, who sells race tickets costing 10 euros each. Customers arrive in some random order: some have only 10 euro banknotes, some have only 20 euro banknotes. Charlie initially has k 10 euro banknotes.

codeforcescompetitive-programmingcombinatoricsmathprobabilities
LeetCode 265 - Paint House II

The problem gives us a matrix called costs, where costs[i][j] represents the cost of painting house i with color j. We must paint every house such that no two adjacent houses use the same color, and we want the minimum total painting cost.

leetcodehardarraydynamic-programming
LeetCode 1421 - NPV Queries

The problem presents two database tables: NPV and Queries. The NPV table contains historical net present value (NPV) dat

leetcodeeasydatabase
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 1104 - Path In Zigzag Labelled Binary Tree

This problem describes an infinite binary tree where nodes are normally arranged level by level, but with a twist in how labels are assigned. In a standard binary tree, nodes in each level are labeled from left to right.

leetcodemediummathtreebinary-tree
LeetCode 1120 - Maximum Average Subtree

This problem asks us to find the maximum average value among all subtrees of a given binary tree. A subtree is defined as any node along with all of its descendants. The average of a subtree is the sum of its node values divided by the number of nodes in that subtree.

leetcodemediumtreedepth-first-searchbinary-tree
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 961 - N-Repeated Element in Size 2N Array

The problem gives us an integer array nums whose length is exactly 2 n. Among all the numbers in the array, there are n + 1 distinct values. One special value appears exactly n times, while every other value appears only once.

leetcodeeasyarrayhash-table
CF 36D - New Game with a Chess Piece

We are asked to analyze a two-player game on an rectangular board. The players take turns moving a single chess piece starting in the top-left corner. On each turn, a player can move the piece one cell right, one cell down, or diagonally cells down-right.

codeforcescompetitive-programminggames
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
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
CF 79B - Colorful Field

We are asked to simulate planting crops on a rectangular field, but with a catch: some cells are wasteland. The field is represented as an n by m grid, with rows numbered from 1 to n and columns from 1 to m.

codeforcescompetitive-programmingimplementationsortings
CF 131C - The World is a Theatre

We have a theatre club with n boys and m girls. A performance group must contain exactly t people, with two extra restrictions: at least 4 of them must be boys, and at least 1 must be a girl. The task is to count how many different valid groups can be formed.

codeforcescompetitive-programmingcombinatoricsmath
LeetCode 1391 - Check if There is a Valid Path in a Grid

The problem presents a grid where each cell represents a street segment with a specific orientation, denoted by a number

leetcodemediumarraydepth-first-searchbreadth-first-searchunion-findmatrix
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 1240 - Tiling a Rectangle with the Fewest Squares

The problem is asking us to completely cover a rectangle of size n x m with the fewest number of squares that have integer side lengths. The rectangle can be tiled with squares of any size, as long as each square fits entirely within the rectangle and there is no overlap.

leetcodehardbacktracking
LeetCode 1388 - Pizza With 3n Slices

In this problem, we are given a circular pizza divided into 3n slices. Each slice has a size represented by the array sl

leetcodehardarraydynamic-programminggreedyheap-(priority-queue)
LeetCode 1734 - Decode XORed Permutation

The problem gives us an array called encoded, which was generated from an unknown permutation array perm. A permutation of the first n positive integers means the array contains every integer from 1 to n exactly once. For example: - [1,2,3] is a valid permutation of 1..

leetcodemediumarraybit-manipulation
CF 70B - Text Messaging

We are given the maximum length of a single SMS message and one complete text consisting of sentences separated by spaces. A sentence always ends with one of ., ?, or !. Words contain only letters.

codeforcescompetitive-programmingexpression-parsinggreedystrings
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 245 - Shortest Word Distance III

The problem gives us an array of strings, wordsDict, and two target words, word1 and word2. We must find the minimum distance between any occurrence of these two words in the array.

leetcodemediumarraystring
LeetCode 1309 - Decrypt String from Alphabet to Integer Mapping

The problem gives us a string containing digits and the '' character. This string encodes lowercase English letters usin

leetcodeeasystring
CF 57E - Chess

We start on an infinite chessboard at square (0, 0). A knight moves using the usual chess move, two cells in one direction and one in the perpendicular direction. Some squares are removed from the board, and the knight is never allowed to stand on them.

codeforcescompetitive-programmingmathshortest-paths
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
LeetCode 86 - Partition List

It looks like you want the full detailed solution guide, but the specific LeetCode problem number and statement are missing from your latest request template. You included the formatting instructions and structure, but not which problem to solve beyond prior context.

leetcodemediumlinked-listtwo-pointers
LeetCode 1534 - Count Good Triplets

The problem asks us to count the number of good triplets in an integer array arr based on three difference constraints a, b, and c.

leetcodeeasyarrayenumeration
LeetCode 1557 - Minimum Number of Vertices to Reach All Nodes

The problem is asking us to identify the minimum set of vertices in a directed acyclic graph (DAG) such that starting from any of these vertices, all other nodes in the graph are reachable.

leetcodemediumgraph-theory
CF 10A - Power Consumption Calculation

Tom uses his laptop during several disjoint time intervals. While he is actively using it, the laptop stays in normal mode and consumes P1 watts per minute. When he stops interacting with the laptop, the machine does not immediately switch to lower-power states.

codeforcescompetitive-programmingimplementation
CF 49E - Common ancestor

Each DNA string evolves by repeatedly applying rules of the form a -> bc. One character is replaced by exactly two characters, and this operation can be repeated any number of times. Starting from some ancestor string, evolution only increases the length.

codeforcescompetitive-programmingdp
LeetCode 916 - Word Subsets

The problem asks us to determine which strings in words1 satisfy all character requirements imposed by every string in words2. A string b is considered a subset of another string a if every character in b appears in a at least as many times as it appears in b.

leetcodemediumarrayhash-tablestring
CF 10E - Greedy Change

We are asked to investigate whether the greedy algorithm for making change can fail with a given set of coin denominations.

codeforcescompetitive-programmingconstructive-algorithms
LeetCode 859 - Buddy Strings

The problem asks whether it is possible to make two strings equal by performing exactly one swap operation on the first string s. A swap operation means choosing two different indices i and j in s and exchanging the characters at those positions.

leetcodeeasyhash-tablestring
CF 33D - Knights

We are given a map of Berland with several control points and circular fences. Each knight occupies a control point. Fences separate the kingdom into regions, and a knight must cross fences to move between control points.

codeforcescompetitive-programminggeometrygraphsshortest-pathssortings
LeetCode 1801 - Number of Orders in the Backlog

This problem simulates a simplified stock exchange order book. Each incoming order is either a buy order or a sell order, and each order contains a price and an amount. Orders are processed strictly in the order they appear in the input.

leetcodemediumarrayheap-(priority-queue)simulation
LeetCode 495 - Teemo Attacking

The problem asks us to calculate the total duration that Ashe is poisoned by Teemo's attacks. Each attack at a given second t causes Ashe to be poisoned for exactly duration seconds, and the poisoning time is inclusive, meaning that the poison effect lasts from time t to t +…

leetcodeeasyarraysimulation
LeetCode 173 - Binary Search Tree Iterator

It looks like your prompt accidentally concatenated two problems. I will answer the second one, LeetCode 173 - Binary Search Tree Iterator, following your required format.

leetcodemediumstacktreedesignbinary-search-treebinary-treeiterator
LeetCode 1638 - Count Substrings That Differ by One Character

The problem asks us to count how many pairs of substrings, one taken from s and one taken from t, differ by exactly one

leetcodemediumhash-tablestringdynamic-programmingenumeration
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 1648 - Sell Diminishing-Valued Colored Balls

Here is the complete, detailed technical solution guide for LeetCode 1648 - Sell Diminishing-Valued Colored Balls follow

leetcodemediumarraymathbinary-searchgreedysortingheap-(priority-queue)
LeetCode 280 - Wiggle Sort

The problem asks us to rearrange an integer array so that it follows a specific alternating pattern called a wiggle sequence. The required relationship is: - nums[0] <= nums[1] - nums[1] = nums[2] - nums[2] <= nums[3] - nums[3] = nums[4] - and so on.

leetcodemediumarraygreedysorting
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
LeetCode 381 - Insert Delete GetRandom O(1) - Duplicates allowed

The problem asks us to design a data structure called RandomizedCollection that behaves like a multiset. Unlike a normal set, duplicate values are allowed.

leetcodehardarrayhash-tablemathdesignrandomized
LeetCode 795 - Number of Subarrays with Bounded Maximum

The problem asks us to count how many contiguous, non-empty subarrays have a maximum element that lies within the inclusive range [left, right]. A subarray is a continuous segment of the original array. For every possible subarray, we look at its maximum value.

leetcodemediumarraytwo-pointers
LeetCode 684 - Redundant Connection

The problem is asking us to identify a redundant edge in a graph that started as a tree. A tree is a connected graph with n nodes and exactly n-1 edges, meaning it has no cycles. The input graph has n nodes and n edges, so by definition, it contains exactly one cycle.

leetcodemediumdepth-first-searchbreadth-first-searchunion-findgraph-theory