# H11. Two Sum

Given an array of integers `nums`

and an integer `target`

, return *indices of the two numbers such that they add up to target*.

You may assume that each input would have **exactly one solution**, and you may not use the *same* element twice.

You can return the answer in any order.

**Example 1:**

**Example 2:**

**Example 3:**

**Solution**:

# H12. Add Two Numbers

You are given two **non-empty** linked lists representing two non-negative integers. The digits are stored in **reverse order**, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

**Example 1:**

**Solution**:

# H114. Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string `""`

.

**Example 1:**

**Solution**:

# H119. Remove Nth Node From End of List

Given the `head`

of a linked list, remove the `nth`

node from the end of the list and return its head.

**Example 1:**

**Solution**:

Note:

We use

`fast`

and`slow`

to reach the n^th^ node from the end of the list cleverly.

# H121. Merge Two Sorted Lists

You are given the heads of two sorted linked lists `list1`

and `list2`

.

Merge the two lists into one **sorted** list. The list should be made by splicing together the nodes of the first two lists.

Return *the head of the merged linked list*.

**Example 1:**

**Solution**:

# H126. Remove Duplicates from Sorted Array

Given an integer array `nums`

sorted in **non-decreasing order**, remove the duplicates **in-place** such that each unique element appears only **once**. The **relative order** of the elements should be kept the **same**. Then return *the number of unique elements in* `nums`

.

Consider the number of unique elements of `nums`

to be `k`

, to get accepted, you need to do the following things:

- Change the array
`nums`

such that the first`k`

elements of`nums`

contain the unique elements in the order they were present in`nums`

initially. The remaining elements of`nums`

are not important as well as the size of`nums`

. - Return
`k`

.

**Example 1:**

**Constraints:**

`1 <= nums.length <= 3 * 104`

`-100 <= nums[i] <= 100`

`nums`

is sorted in**non-decreasing**order.

**Solution**:

Note: We ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements.

# H145. Jump Game II

You are given a **0-indexed** array of integers `nums`

of length `n`

. You are initially positioned at `nums[0]`

.

Each element `nums[i]`

represents the maximum length of a forward jump from index `i`

. In other words, if you are at `nums[i]`

, you can jump to any `nums[i + j]`

where:

`0 <= j <= nums[i]`

and`i + j < n`

Return *the minimum number of jumps to reach* `nums[n - 1]`

. The test cases are generated such that you can reach `nums[n - 1]`

.

**Example 1:**

**Solution**:

# H149. Group Anagrams

Given an array of strings `strs`

, group **the anagrams** together. You can return the answer in **any order**.

An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

**Example 1:**

**Solution**:

Note: In scenarios where key-value pairs are frequently added or deleted, Map may perform better than Object.

# H153. Maximum Subarray

Given an integer array `nums`

, find the subarray with the largest sum, and return *its sum*.

**Example 1:**

**Solution**:

Note:

`dp[i] = nums[i] + max(0, dp[i-1])`

# H155. Jump Game

You are given an integer array `nums`

. You are initially positioned at the array's **first index**, and each element in the array represents your maximum jump length at that position.

Return `true`

*if you can reach the last index, or* `false`

*otherwise*.

**Example 1:**

**Solution**:

# H171. Simplify Path

Given a string `path`

, which is an **absolute path** (starting with a slash `'/'`

) to a file or directory in a Unix-style file system, convert it to the simplified **canonical path**.

In a Unix-style file system, a period `'.'`

refers to the current directory, a double period `'..'`

refers to the directory up a level, and any multiple consecutive slashes (i.e. `'//'`

) are treated as a single slash `'/'`

. For this problem, any other format of periods such as `'...'`

are treated as file/directory names.

The **canonical path** should have the following format:

- The path starts with a single slash
`'/'`

. - Any two directories are separated by a single slash
`'/'`

. - The path does not end with a trailing
`'/'`

. - The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period
`'.'`

or double period`'..'`

)

Return *the simplified canonical path*.

**Example 1:**

**Example 2:**

**Solution**:

# H180. Remove Duplicates from Sorted Array II

Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same.

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

Return k after placing the final result in the first k slots of nums.

Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

**Example 1:**

**Solution**:

# H188. Merge Sorted Array

You are given two integer arrays `nums1`

and `nums2`

, sorted in **non-decreasing order**, and two integers `m`

and `n`

, representing the number of elements in `nums1`

and `nums2`

respectively.

**Merge** `nums1`

and `nums2`

into a single array sorted in **non-decreasing order**.

The final sorted array should not be returned by the function, but instead be *stored inside the array* `nums1`

. To accommodate this, `nums1`

has a length of `m + n`

, where the first `m`

elements denote the elements that should be merged, and the last `n`

elements are set to `0`

and should be ignored. `nums2`

has a length of `n`

.

**Example 1:**

**Solution**:

# H192. Reverse Linked List II

Given the `head`

of a singly linked list and two integers `left`

and `right`

where `left <= right`

, reverse the nodes of the list from position `left`

to position `right`

, and return *the reversed list*.

**Example 1:**

**Solution**:

# H1100. Same Tree

Given the roots of two binary trees `p`

and `q`

, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.

**Example 1:**

**Solution**:

# H1101. Symmetric Tree

Given the `root`

of a binary tree, *check whether it is a mirror of itself* (i.e., symmetric around its center).

**Example 1:**

**Solution**:

# H1112. Path Sum

Given the `root`

of a binary tree and an integer `targetSum`

, return `true`

if the tree has a **root-to-leaf** path such that adding up all the values along the path equals `targetSum`

.

A **leaf** is a node with no children.

**Example 1:**

**Solution**:

# H1114. Flatten Binary Tree to Linked List

Given the `root`

of a binary tree, flatten the tree into a "linked list":

- The "linked list" should use the same
`TreeNode`

class where the`right`

child pointer points to the next node in the list and the`left`

child pointer is always`null`

. - The "linked list" should be in the same order as a
**pre-order****traversal**of the binary tree.

**Example 1:**

**Solution**:

Note: Here we use

`Morris Traversal`

.

# H1108. Convert Sorted Array to Binary Search Tree

Given an integer array `nums`

where the elements are sorted in **ascending order**, convert *it to a* **height-balanced** binary search tree.

**Example 1:**

**Solution**:

# H1117. Populating Next Right Pointers in Each Node II

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to `NULL`

.

Initially, all next pointers are set to `NULL`

.

**Example 1:**

**Solution**:

# H1121. Best Time to Buy and Sell Stock

You are given an array `prices`

where `prices[i]`

is the price of a given stock on the `ith`

day.

You want to maximize your profit by choosing a **single day** to buy one stock and choosing a **different day in the future** to sell that stock.

Return *the maximum profit you can achieve from this transaction*. If you cannot achieve any profit, return `0`

.

**Example 1:**

**Example 2:**

**Solution**:

# H1128. Longest Consecutive Sequence

Given an unsorted array of integers `nums`

, return *the length of the longest consecutive elements sequence.*

You must write an algorithm that runs in `O(n)`

time.

**Example 1:**

**Solution**:

Note: Every number will be accessed at most twice, so the time complexity is

`O(n)`

.

# H1130. Surrounded Regions

Given an `m x n`

matrix `board`

containing `'X'`

and `'O'`

, *capture all regions that are 4-directionally surrounded by* `'X'`

.

A region is **captured** by flipping all `'O'`

s into `'X'`

s in that surrounded region.

**Example 1:**

**Solution**:

Note:

- We have to traverse
`board`

's boader once to find "O".- If we find "O", run dfs on this "O" and rename all the adjacent "O" as "S" which stands for "Saving".
- Traverse
`board`

again to rename all the "O" as "X" and "S" as "O".

# H1133. Clone Graph

Given a reference of a node in a **connected** undirected graph.

Return a **deep copy** (clone) of the graph.

Each node in the graph contains a value (`int`

) and a list (`List[Node]`

) of its neighbors.

**Test case format:**

For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with `val == 1`

, the second node with `val == 2`

, and so on. The graph is represented in the test case using an adjacency list.

**An adjacency list** is a collection of unordered **lists** used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.

The given node will always be the first node with `val = 1`

. You must return the **copy of the given node** as a reference to the cloned graph.

**Example 1:**

**Solution**:

# H1134. Gas Station

There are `n`

gas stations along a circular route, where the amount of gas at the `ith`

station is `gas[i]`

.

You have a car with an unlimited gas tank and it costs `cost[i]`

of gas to travel from the `ith`

station to its next `(i + 1)th`

station. You begin the journey with an empty tank at one of the gas stations.

Given two integer arrays `gas`

and `cost`

, return *the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return* `-1`

. If there exists a solution, it is **guaranteed** to be **unique**

**Example 1:**

**Solution**:

# H1135. Candy

There are `n`

children standing in a line. Each child is assigned a rating value given in the integer array `ratings`

.

You are giving candies to these children subjected to the following requirements:

- Each child must have at least one candy.
- Children with a higher rating get more candies than their neighbors.

Return *the minimum number of candies you need to have to distribute the candies to the children*.

**Example 1:**

**Solution**:

Note:

Initialize`Candies`

array filled with 1.- Conduct
Forward pass&Backward passto ensure the current candy number is less than or more neighbor candy numbers based on comparison.Sum it all up.

# H1141. Linked List Cycle

Given `head`

, the head of a linked list, determine if the linked list has a cycle in it.

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next`

pointer. Internally, `pos`

is used to denote the index of the node that tail's `next`

pointer is connected to. **Note that pos is not passed as a parameter**.

Return `true`

*if there is a cycle in the linked list*. Otherwise, return `false`

.

**Example 1:**

**Solution**:

# H1169. Majority Element

Given an array `nums`

of size `n`

, return *the majority element*.

The majority element is the element that appears more than `⌊n / 2⌋`

times. You may assume that the majority element always exists in the array.

**Example 1:**

**Solution**:

Note: Use Boyer-Moore Voting Algorithm.

# H1199. Binary Tree Right Side View

Given the `root`

of a binary tree, imagine yourself standing on the **right side** of it, return *the values of the nodes you can see ordered from top to bottom*.

**Example 1:**

**Solution**:

# H1200. Number of Islands

Given an `m x n`

2D binary grid `grid`

which represents a map of `'1'`

s (land) and `'0'`

s (water), return *the number of islands*.

An **island** is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

**Example 1:**

**Solution**:

# H1206. Reverse Linked List

Given the `head`

of a singly linked list, reverse the list, and return *the reversed list*.

**Example 1:**

**Solution**:

# H1207. Course Schedule

There are a total of `numCourses`

courses you have to take, labeled from `0`

to `numCourses - 1`

. You are given an array `prerequisites`

where `prerequisites[i] = [ai, bi]`

indicates that you **must** take course `bi`

first if you want to take course `ai`

.

- For example, the pair
`[0, 1]`

, indicates that to take course`0`

you have to first take course`1`

.

Return `true`

if you can finish all courses. Otherwise, return `false`

.

**Example 1:**

**Solution**:

Note:

# H1228. Summary Ranges

You are given a **sorted unique** integer array `nums`

.

A **range** `[a,b]`

is the set of all integers from `a`

to `b`

(inclusive).

Return *the smallest sorted list of ranges that cover all the numbers in the array exactly*. That is, each element of

`nums`

is covered by exactly one of the ranges, and there is no integer `x`

such that `x`

is in one of the ranges but not in `nums`

.Each range `[a,b]`

in the list should be output as:

`"a->b"`

if`a != b`

`"a"`

if`a == b`

**Example 1:**

**Solution**:

# H1238. Product of Array Except Self

Given an integer array `nums`

, return *an array* `answer`

*such that* `answer[i]`

*is equal to the product of all the elements of* `nums`

*except* `nums[i]`

.

The product of any prefix or suffix of `nums`

is **guaranteed** to fit in a **32-bit** integer.

You must write an algorithm that runs in `O(n)`

time and without using the division operation.

**Example 1:**

**Solution**:

# H1283. Move Zeroes

Given an integer array `nums`

, move all `0`

's to the end of it while maintaining the relative order of the non-zero elements.

**Note** that you must do this in-place without making a copy of the array.

**Example 1:**

**Solution**:

# H1290. Word Pattern

Given a `pattern`

and a string `s`

, find if `s`

follows the same pattern.

Here **follow** means a full match, such that there is a bijection between a letter in `pattern`

and a **non-empty** word in `s`

.

**Example 1:**

**Example 2:**

**Solution**:

# H1334. Increasing Triplet Subsequence

Given an integer array `nums`

, return `true`

*if there exists a triple of indices* `(i, j, k)`

*such that* `i < j < k`

*and* `nums[i] < nums[j] < nums[k]`

. If no such indices exists, return `false`

.

**Example 1:**

**Example 2:**

**Solution**:

# H1399. Evaluate Division

You are given an array of variable pairs `equations`

and an array of real numbers `values`

, where `equations[i] = [Ai, Bi]`

and `values[i]`

represent the equation `Ai / Bi = values[i]`

. Each `Ai`

or `Bi`

is a string that represents a single variable.

You are also given some `queries`

, where `queries[j] = [Cj, Dj]`

represents the `jth`

query where you must find the answer for `Cj / Dj = ?`

.

Return *the answers to all queries*. If a single answer cannot be determined, return `-1.0`

.

**Note:** The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.

**Note:** The variables that do not occur in the list of equations are undefined, so the answer cannot be determined for them.

**Example 1:**

**Solution**:

# H1530. Minimum Absolute Difference in BST

Given the `root`

of a Binary Search Tree (BST), return *the minimum absolute difference between the values of any two different nodes in the tree*.

**Example 1:**

**Solution**:

# H1559. Maximum Depth of N-ary Tree

Given a n-ary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

*Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).*

**Example 1:**

**Solution**:

# H1590. N-ary Tree Postorder Traversal

Given the `root`

of an n-ary tree, return *the postorder traversal of its nodes' values*.

Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)

**Example 1:**

**Solution**:

# H1617. Merge Two Binary Trees

You are given two binary trees `root1`

and `root2`

.

Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree.

Return *the merged tree*.

**Note:** The merging process must start from the root nodes of both trees.

**Example 1:**

**Solution**:

# H1637. Average of Levels in Binary Tree

Given the `root`

of a binary tree, return *the average value of the nodes on each level in the form of an array*. Answers within `10-5`

of the actual answer will be accepted.

**Example 1:**

**Solution**:

# H1746. Min Cost Climbing Stairs

You are given an integer array `cost`

where `cost[i]`

is the cost of `ith`

step on a staircase. Once you pay the cost, you can either climb one or two steps.

You can either start from the step with index `0`

, or the step with index `1`

.

Return *the minimum cost to reach the top of the floor*.

**Example 1:**

**Solution**:

Hint:

- Build an array dp where dp[i] is the minimum cost to climb to the top starting from the ith staircase.
- Assuming we have n staircase labeled from 0 to n - 1 and assuming the top is n, then dp[n] = 0, marking that if you are at the top, the cost is 0.
- Now, looping from n - 1 to 0, the dp[i] = cost[i] + min(dp[i + 1], dp[i + 2]). The answer will be the minimum of dp[0] and dp[1]

# H1807. Max Increase to Keep City Skyline

There is a city composed of `n x n`

blocks, where each block contains a single building shaped like a vertical square prism. You are given a **0-indexed** `n x n`

integer matrix `grid`

where `grid[r][c]`

represents the **height** of the building located in the block at row `r`

and column `c`

.

A city's **skyline** is the outer contour formed by all the building when viewing the side of the city from a distance. The **skyline** from each cardinal direction north, east, south, and west may be different.

We are allowed to increase the height of **any number of buildings by any amount** (the amount can be different per building). The height of a `0`

-height building can also be increased. However, increasing the height of a building should **not** affect the city's **skyline** from any cardinal direction.

Return *the maximum total sum that the height of the buildings can be increased by without changing the city's skyline from any cardinal direction*.

**Example 1:**

**Solution**:

# H1841. Keys and Rooms

There are `n`

rooms labeled from `0`

to `n - 1`

and all the rooms are locked except for room `0`

. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key.

When you visit a room, you may find a set of **distinct keys** in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms.

Given an array `rooms`

where `rooms[i]`

is the set of keys that you can obtain if you visited room `i`

, return `true`

*if you can visit all the rooms, or*

`false`

*otherwise*.

**Example 1:**

**Solution**:

# H1872. Leaf-Similar Trees

Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a **leaf value sequence***.*

For example, in the given tree above, the leaf value sequence is `(6, 7, 4, 9, 8)`

.

Two binary trees are considered *leaf-similar* if their leaf value sequence is the same.

Return `true`

if and only if the two given trees with head nodes `root1`

and `root2`

are leaf-similar.

**Example 1:**

**Solution**:

# H1897. Increasing Order Search Tree

Given the `root`

of a binary search tree, rearrange the tree in **in-order** so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child.

**Example 1:**

**Solution**:

# H1933. Number of Recent Calls

You have a `RecentCounter`

class which counts the number of recent requests within a certain time frame.

Implement the `RecentCounter`

class:

`RecentCounter()`

Initializes the counter with zero recent requests.`int ping(int t)`

Adds a new request at time`t`

, where`t`

represents some time in milliseconds, and returns the number of requests that has happened in the past`3000`

milliseconds (including the new request). Specifically, return the number of requests that have happened in the inclusive range`[t - 3000, t]`

.

It is **guaranteed** that every call to `ping`

uses a strictly larger value of `t`

than the previous call.

**Example 1:**

**Solution**:

Note:

- I suddenly found we can write more than one condition in
`while`

loop.

# H1938. Range Sum of BST

Given the `root`

node of a binary search tree and two integers `low`

and `high`

, return *the sum of values of all nodes with a value in the inclusive range*

`[low, high]`

.**Example 1:**

**Solution**:

# H1997. Find the Town Judge

In a town, there are `n`

people labeled from `1`

to `n`

. There is a rumor that one of these people is secretly the town judge.

If the town judge exists, then:

- The town judge trusts nobody.
- Everybody (except for the town judge) trusts the town judge.
- There is exactly one person that satisfies properties
**1**and**2**.

You are given an array `trust`

where `trust[i] = [ai, bi]`

representing that the person labeled `ai`

trusts the person labeled `bi`

. If a trust relationship does not exist in `trust`

array, then such a trust relationship does not exist.

Return *the label of the town judge if the town judge exists and can be identified, or return* `-1`

*otherwise*.

**Example 1:**

**Example 2:**

**Solution**:

# H11021. Remove Outermost Parentheses

A valid parentheses string is either empty `""`

, `"(" + A + ")"`

, or `A + B`

, where `A`

and `B`

are valid parentheses strings, and `+`

represents string concatenation.

- For example,
`""`

,`"()"`

,`"(())()"`

, and`"(()(()))"`

are all valid parentheses strings.

A valid parentheses string `s`

is primitive if it is nonempty, and there does not exist a way to split it into `s = A + B`

, with `A`

and `B`

nonempty valid parentheses strings.

Given a valid parentheses string `s`

, consider its primitive decomposition: `s = P1 + P2 + ... + Pk`

, where `Pi`

are primitive valid parentheses strings.

Return `s`

*after removing the outermost parentheses of every primitive string in the primitive decomposition of* `s`

.

**Example 1:**

**Solution**:

Note:

- Use
`const`

to declare`str`

.`stack`

is not necessarily to be`[]`

, because we don't need to use value of this array. So we might as well use Number to check if each part comes to an end.

# H11207. Unique Number of Occurrences

Given an array of integers `arr`

, return `true`

*if the number of occurrences of each value in the array is unique or*

`false`

*otherwise*.

**Example 1:**

**Example 2:**

**Solution**:

# H11221. Split a String in Balanced Strings

**Balanced** strings are those that have an equal quantity of `'L'`

and `'R'`

characters.

Given a **balanced** string `s`

, split it into some number of substrings such that:

- Each substring is balanced.

Return *the maximum number of balanced strings you can obtain.*

**Example 1:**

**Solution**:

# H11282. Group the People Given the Group Size They Belong To

There are `n`

people that are split into some unknown number of groups. Each person is labeled with a **unique ID** from `0`

to `n - 1`

.

You are given an integer array `groupSizes`

, where `groupSizes[i]`

is the size of the group that person `i`

is in. For example, if `groupSizes[1] = 3`

, then person `1`

must be in a group of size `3`

.

Return *a list of groups such that each person i is in a group of size groupSizes[i]*.

Each person should appear in **exactly one group**, and every person must be in a group. If there are multiple answers, **return any of them**. It is **guaranteed** that there will be **at least one** valid solution for the given input.

**Example 1:**

**Example 2:**

**Solution**:

Note: It took me 40 minutes to figure it out.

`if`

statement here is the point.

# H11379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree

Given two binary trees `original`

and `cloned`

and given a reference to a node `target`

in the original tree.

The `cloned`

tree is a **copy of** the `original`

tree.

Return *a reference to the same node* in the `cloned`

tree.

**Note** that you are **not allowed** to change any of the two trees or the `target`

node and the answer **must be** a reference to a node in the `cloned`

tree.

**Example 1:**

**Solution**:

# H11402. Reducing Dishes

A chef has collected data on the `satisfaction`

level of his `n`

dishes. Chef can cook any dish in 1 unit of time.

**Like-time coefficient** of a dish is defined as the time taken to cook that dish including previous dishes multiplied by its satisfaction level i.e. `time[i] * satisfaction[i]`

.

Return the maximum sum of **like-time coefficient** that the chef can obtain after preparing some amount of dishes.

Dishes can be prepared in **any** order and the chef can discard some dishes to get this maximum value.

**Example 1:**

**Solution**:

Note: If sum < 0, that means we don't need the rest of them anymore. Look, [-4, 5] and [5]，which sum of like-time coefficient is bigger? Definitely the former one, so we should ensure sum is more than 0 to keep the maximum sum.

# H11512. Number of Good Pairs

Given an array of integers `nums`

, return *the number of good pairs*.

A pair `(i, j)`

is called *good* if `nums[i] == nums[j]`

and `i`

< `j`

.

**Example 1:**

**Example 2:**

**Solution**:

# H11539. Kth Missing Positive Number

Given an array `arr`

of positive integers sorted in a **strictly increasing order**, and an integer `k`

.

Return *the* `kth`

**positive** integer that is **missing** from this array.

**Example 1:**

**Example 2:**

**Solution**:

# H11615. Maximal Network Rank

There is an infrastructure of `n`

cities with some number of `roads`

connecting these cities. Each `roads[i] = [ai, bi]`

indicates that there is a bidirectional road between cities `ai`

and `bi`

.

The **network rank** of **two different cities** is defined as the total number of **directly** connected roads to **either** city. If a road is directly connected to both cities, it is only counted **once**.

The **maximal network rank** of the infrastructure is the **maximum network rank** of all pairs of different cities.

Given the integer `n`

and the array `roads`

, return *the maximal network rank of the entire infrastructure*.

**Example 1:**

**img**

**Solution**:

# H11640. Check Array Formation Through Concatenation

You are given an array of **distinct** integers `arr`

and an array of integer arrays `pieces`

, where the integers in `pieces`

are **distinct**. Your goal is to form `arr`

by concatenating the arrays in `pieces`

**in any order**. However, you are **not** allowed to reorder the integers in each array `pieces[i]`

.

Return `true`

*if it is possible* *to form the array* `arr`

*from* `pieces`

. Otherwise, return `false`

.

**Example 1:**

**Example 2:**

**Example 3:**

**Solution**:

# H11689. Partitioning Into Minimum Number Of Deci-Binary Numbers

A decimal number is called **deci-binary** if each of its digits is either `0`

or `1`

without any leading zeros. For example, `101`

and `1100`

are **deci-binary**, while `112`

and `3001`

are not.

Given a string `n`

that represents a positive decimal integer, return *the minimum number of positive deci-binary numbers needed so that they sum up to*

`n`

*.*

**Example 1:**

**Example 2:**

**Example 3:**

**Solution**:

Note: The greediness lies in finding the biggest digit in

`n`

at first.

# H11848. Minimum Distance to the Target Element

Given an integer array `nums`

**(0-indexed)** and two integers `target`

and `start`

, find an index `i`

such that `nums[i] == target`

and `abs(i - start)`

is **minimized**. Note that `abs(x)`

is the absolute value of `x`

.

Return `abs(i - start)`

.

It is **guaranteed** that `target`

exists in `nums`

.

**Example 1:**

**Example 2:**

**Solution**:

# H11971. Find if Path Exists in Graph

There is a **bi-directional** graph with `n`

vertices, where each vertex is labeled from `0`

to `n - 1`

(**inclusive**). The edges in the graph are represented as a 2D integer array `edges`

, where each `edges[i] = [ui, vi]`

denotes a bi-directional edge between vertex `ui`

and vertex `vi`

. Every vertex pair is connected by **at most one** edge, and no vertex has an edge to itself.

You want to determine if there is a **valid path** that exists from vertex `source`

to vertex `destination`

.

Given `edges`

and the integers `n`

, `source`

, and `destination`

, return `true`

*if there is a valid path from*

`source`

*to*

`destination`

*, or*

`false`

*otherwise**.*

**Example 1:**

**Solution**:

# H12006. Count Number of Pairs With Absolute Difference K

Given an integer array `nums`

and an integer `k`

, return *the number of pairs* `(i, j)`

*where* `i < j`

*such that* `|nums[i] - nums[j]| == k`

.

The value of `|x|`

is defined as:

`x`

if`x >= 0`

.`-x`

if`x < 0`

.

**Example 1:**

**Example 2:**

**Solution**:

# H12224. Minimum Number of Operations to Convert Time

You are given two strings `current`

and `correct`

representing two **24-hour times**.

24-hour times are formatted as `"HH:MM"`

, where `HH`

is between `00`

and `23`

, and `MM`

is between `00`

and `59`

. The earliest 24-hour time is `00:00`

, and the latest is `23:59`

.

In one operation you can increase the time `current`

by `1`

, `5`

, `15`

, or `60`

minutes. You can perform this operation **any** number of times.

Return *the minimum number of operations needed to convert*

`current`

*to*

`correct`

.**Example 1:**

**Solution**:

Note: You don't need to use

`while`

, just calculate it.

# H12265. Count Nodes Equal to Average of Subtree

Given the `root`

of a binary tree, return *the number of nodes where the value of the node is equal to the average of the values in its subtree*.

**Note:**

- The
**average**of`n`

elements is the**sum**of the`n`

elements divided by`n`

and**rounded down**to the nearest integer. - A
**subtree**of`root`

is a tree consisting of`root`

and all of its descendants.

**Example 1:**

**Solution**:

# H12325. Decode the Message

You are given the strings `key`

and `message`

, which represent a cipher key and a secret message, respectively. The steps to decode `message`

are as follows:

- Use the
**first**appearance of all 26 lowercase English letters in`key`

as the**order**of the substitution table. - Align the substitution table with the regular English alphabet.
- Each letter in
`message`

is then**substituted**using the table. - Spaces
`' '`

are transformed to themselves.

- For example, given
`key = "**hap**p**y** **bo**y"`

(actual key would have**at least one**instance of each letter in the alphabet), we have the partial substitution table of (`'h' -> 'a'`

,`'a' -> 'b'`

,`'p' -> 'c'`

,`'y' -> 'd'`

,`'b' -> 'e'`

,`'o' -> 'f'`

).

Return *the decoded message*.

**Example 1:**

**Example 2:**

**Solution**:

# H12409. Count Days Spent Together

Alice and Bob are traveling to Rome for separate business meetings.

You are given 4 strings `arriveAlice`

, `leaveAlice`

, `arriveBob`

, and `leaveBob`

. Alice will be in the city from the dates `arriveAlice`

to `leaveAlice`

(**inclusive**), while Bob will be in the city from the dates `arriveBob`

to `leaveBob`

(**inclusive**). Each will be a 5-character string in the format `"MM-DD"`

, corresponding to the month and day of the date.

Return *the total number of days that Alice and Bob are in Rome together.*

You can assume that all dates occur in the **same** calendar year, which is **not** a leap year. Note that the number of days per month can be represented as: `[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]`

.

**Example 1:**

**Solution**:

# H12824. Count Pairs Whose Sum is Less than Target

Given a **0-indexed** integer array `nums`

of length `n`

and an integer `target`

, return *the number of pairs* `(i, j)`

*where* `0 <= i < j < n`

*and* `nums[i] + nums[j] < target`

.

**Example 1:**

**Solution**:

# H12864. Maximum Odd Binary Number

You are given a **binary** string `s`

that contains at least one `'1'`

.

You have to **rearrange** the bits in such a way that the resulting binary number is the **maximum odd binary number** that can be created from this combination.

Return *a string representing the maximum odd binary number that can be created from the given combination.*

**Note** that the resulting string **can** have leading zeros.

**Example 1:**

**Solution**:

Note: The strategy is that we should put one

`1`

at the end and the rest of them should come first.