0% found this document useful (0 votes)
129 views

Infosys Leet Code

Uploaded by

Deepthi nagella
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
129 views

Infosys Leet Code

Uploaded by

Deepthi nagella
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 41

1.

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:

Input: nums = [2,7,11,15], target = 9

Output: [0,1]

Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6

Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6

Output: [0,1]

Constraints:

 2 <= nums.length <= 10 4

 -10 <= nums[i] <= 10


9 9

 -10 <= target <= 10


9 9

 Only one valid answer exists.

Follow-up: Can you come up with an algorithm that is less than O(n ) time complexity?
2

3. Longest Substring Without Repeating Characters


Given a string s, find the length of the longest substring without repeating characters.

Example 1:

Input: s = "abcabcbb"

Output: 3

Explanation: The answer is "abc", with the length of 3.

Example 2:

Input: s = "bbbbb"

Output: 1

Explanation: The answer is "b", with the length of 1.


Example 3:

Input: s = "pwwkew"

Output: 3

Explanation: The answer is "wke", with the length of 3.

Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.

Constraints:

 0 <= s.length <= 5 * 10 4

 s consists of English letters, digits, symbols and spaces.

5. Longest Palindromic Substring


Given a string s, return the longest palindromic substring in s.

Example 1:

Input: s = "babad"

Output: "bab"

Explanation: "aba" is also a valid answer.

Example 2:

Input: s = "cbbd"

Output: "bb"

Constraints:

 1 <= s.length <= 1000


 s consist of only digits and English letters.

7. Reverse Integer
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-2 , 2
31 31
- 1], then
return 0.

Assume the environment does not allow you to store 64-bit integers (signed or unsigned).

Example 1:

Input: x = 123

Output: 321

Example 2:

Input: x = -123

Output: -321
Example 3:

Input: x = 120

Output: 21

Constraints:

 -231
<= x <= 2
31
- 1

15. 3Sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] +
nums[k] == 0.

Notice that the solution set must not contain duplicate triplets.

Example 1:

Input: nums = [-1,0,1,2,-1,-4]

Output: [[-1,-1,2],[-1,0,1]]

Explanation:

nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.

nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.

nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.

The distinct triplets are [-1,0,1] and [-1,-1,2].

Notice that the order of the output and the order of the triplets does not matter.

Example 2:

Input: nums = [0,1,1]

Output: []

Explanation: The only possible triplet does not sum up to 0.

Example 3:

Input: nums = [0,0,0]

Output: [[0,0,0]]

Explanation: The only possible triplet sums up to 0.

Constraints:

 3 <= nums.length <= 3000


 -10 <= nums[i] <= 10
5 5
18. 4Sum
Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that:

 0 <= a, b, c, d < n
 a, b, c, and d are distinct.
 nums[a] + nums[b] + nums[c] + nums[d] == target

You may return the answer in any order.

Example 1:

Input: nums = [1,0,-1,0,-2,2], target = 0

Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]

Example 2:

Input: nums = [2,2,2,2,2], target = 8

Output: [[2,2,2,2]]

Constraints:

 1 <= nums.length <= 200


 -10 <= nums[i] <= 10
9 9

 -10 <= target <= 10


9 9

20. Valid Parentheses


Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

1. Open brackets must be closed by the same type of brackets.


2. Open brackets must be closed in the correct order.
3. Every close bracket has a corresponding open bracket of the same type.

Example 1:

Input: s = "()"

Output: true

Example 2:

Input: s = "()[]{}"

Output: true

Example 3:

Input: s = "(]"

Output: false
Constraints:

 1 <= s.length <= 10 4

 s consists of parentheses only '()[]{}'.

22. Generate Parentheses


Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

Example 1:

Input: n = 3

Output: ["((()))","(()())","(())()","()(())","()()()"]

Example 2:

Input: n = 1

Output: ["()"]

Constraints:

 1 <= n <= 8

53. Maximum Subarray


Given an integer array nums, find the subarray with the largest sum, and return its sum.

Example 1:

Input: nums = [-2,1,-3,4,-1,2,1,-5,4]

Output: 6

Explanation: The subarray [4,-1,2,1] has the largest sum 6.

Example 2:

Input: nums = [1]

Output: 1

Explanation: The subarray [1] has the largest sum 1.

Example 3:

Input: nums = [5,4,-1,7,8]

Output: 23

Explanation: The subarray [5,4,-1,7,8] has the largest sum 23.

Constraints:
 1 <= nums.length <= 10 5

 -10 <= nums[i] <= 10


4 4

Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

55. 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:

Input: nums = [2,3,1,1,4]

Output: true

Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.

Example 2:

Input: nums = [3,2,1,0,4]

Output: false

Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach
the last index.

Constraints:

 1 <= nums.length <= 10 4

 0 <= nums[i] <= 10 5

SOLUTIONS:

JAVA

enum Index {

GOOD, BAD, UNKNOWN

public class Solution {

Index[] memo;
public boolean canJumpFromPosition(int position, int[] nums) {

if (memo[position] != Index.UNKNOWN) {

return memo[position] == Index.GOOD ? true : false;

int furthestJump = Math.min(position + nums[position], nums.length - 1);

for (int nextPosition = position + 1; nextPosition <= furthestJump; nextPosition++) {

if (canJumpFromPosition(nextPosition, nums)) {

memo[position] = Index.GOOD;

return true;

memo[position] = Index.BAD;

return false;

public boolean canJump(int[] nums) {

memo = new Index[nums.length];

for (int i = 0; i < memo.length; i++) {

memo[i] = Index.UNKNOWN;

memo[memo.length - 1] = Index.GOOD;

return canJumpFromPosition(0, nums);

}
}

62. Unique Paths


There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right
corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time.

Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner.

The test cases are generated so that the answer will be less than or equal to 2 * 10 .
9

Example 1:

Input: m = 3, n = 7

Output: 28

Example 2:

Input: m = 3, n = 2

Output: 3

Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:

1. Right -> Down -> Down

2. Down -> Down -> Right

3. Down -> Right -> Down

Constraints:

 1 <= m, n <= 100

73. Set Matrix Zeroes


Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's.

You must do it in place.

Example 1:
Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]

Output: [[1,0,1],[0,0,0],[1,0,1]]

Example 2:

Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]

Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]

Constraints:

 m == matrix.length
 n == matrix[0].length
 1 <= m, n <= 200
 -231
<= matrix[i][j] <= 2 31
- 1

Follow up:

 A straightforward solution using O(mn) space is probably a bad idea.


 A simple improvement uses O(m + n) space, but still not the best solution.
 Could you devise a constant space solution?

75. Sort Colors


Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red,
white, and blue.

We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.
You must solve this problem without using the library's sort function.

Example 1:

Input: nums = [2,0,2,1,1,0]

Output: [0,0,1,1,2,2]

Example 2:

Input: nums = [2,0,1]

Output: [0,1,2]

Constraints:

 n == nums.length
 1 <= n <= 300
 nums[i] is either 0, 1, or 2.

Follow up: Could you come up with a one-pass algorithm using only constant extra space?

88. 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:

Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3

Output: [1,2,2,3,5,6]

Explanation: The arrays we are merging are [1,2,3] and [2,5,6].

The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.

Example 2:

Input: nums1 = [1], m = 1, nums2 = [], n = 0

Output: [1]

Explanation: The arrays we are merging are [1] and [].


The result of the merge is [1].

Example 3:

Input: nums1 = [0], m = 0, nums2 = [1], n = 1

Output: [1]

Explanation: The arrays we are merging are [] and [1].

The result of the merge is [1].

Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result
can fit in nums1.

Constraints:

 nums1.length == m + n
 nums2.length == n
 0 <= m, n <= 200
 1 <= m + n <= 200
 -109 <= nums1[i], nums2[j] <= 109

Follow up: Can you come up with an algorithm that runs in O(m + n) time?

Solutions:

class Solution {

public void merge(int[] nums1, int m, int[] nums2, int n) {

for (int i = 0; i < n; i++) {

nums1[i + m] = nums2[i];

Arrays.sort(nums1);

Python3

class Solution:

def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""

Do not return anything, modify nums1 in-place instead.

"""

# Write the elements of num2 into the end of nums1.

for i in range(n):

nums1[i + m] = nums2[i]

# Sort nums1 list in-place.

nums1.sort()

118. Pascal's Triangle


Given an integer numRows, return the first numRows of Pascal's triangle.

In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:

Example 1:

Input: numRows = 5

Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]

Example 2:

Input: numRows = 1

Output: [[1]]

Constraints:
 1 <= numRows <= 30

121. 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:

Input: prices = [7,1,5,3,6,4]

Output: 5

Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.

Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.

Example 2:

Input: prices = [7,6,4,3,1]

Output: 0

Explanation: In this case, no transactions are done and the max profit = 0.

Constraints:

 1 <= prices.length <= 105


 0 <= prices[i] <= 104

Solutions:

Java

public class Solution {

public int maxProfit(int prices[]) {

int maxprofit = 0;

for (int i = 0; i < prices.length - 1; i++) {

for (int j = i + 1; j < prices.length; j++) {

int profit = prices[j] - prices[i];


if (profit > maxprofit)

maxprofit = profit;

return maxprofit;

Python3

class Solution:

def maxProfit(self, prices: List[int]) -> int:

max_profit = 0

for i in range(len(prices) - 1):

for j in range(i + 1, len(prices)):

profit = prices[j] - prices[i]

if profit > max_profit:

max_profit = profit

return max_profit

125. Valid Palindrome


A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward
and backward. Alphanumeric characters include letters and numbers.

Given a string s, return true if it is a palindrome, or false otherwise.

Example 1:

Input: s = "A man, a plan, a canal: Panama"

Output: true

Explanation: "amanaplanacanalpanama" is a palindrome.

Example 2:

Input: s = "race a car"

Output: false
Explanation: "raceacar" is not a palindrome.

Example 3:

Input: s = " "

Output: true

Explanation: s is an empty string "" after removing non-alphanumeric characters.

Since an empty string reads the same forward and backward, it is a palindrome.

Constraints:

 1 <= s.length <= 2 * 10 5

 s consists only of printable ASCII characters.

152. Maximum Product Subarray


Given an integer array nums, find a subarray that has the largest product, and return the product.

The test cases are generated so that the answer will fit in a 32-bit integer.

Example 1:

Input: nums = [2,3,-2,4]

Output: 6

Explanation: [2,3] has the largest product 6.

Example 2:

Input: nums = [-2,0,-1]

Output: 0

Explanation: The result cannot be 2, because [-2,-1] is not a subarray.

Constraints:

 1 <= nums.length <= 2 * 10 4

 -10 <= nums[i] <= 10


 The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

176. Second Highest Salary


Medium
3133878Add to ListShare
SQL Schema

Table: Employee

+-------------+------+

| Column Name | Type |


+-------------+------+

| id | int |

| salary | int |

+-------------+------+

id is the primary key (column with unique values) for this table.

Each row of this table contains information about the salary of an employee.

Write a solution to find the second highest salary from the Employee table. If there is no second highest salary, return null (return None in Pandas).

The result format is in the following example.

Example 1:

Input:

Employee table:

+----+--------+

| id | salary |

+----+--------+

| 1 | 100 |

| 2 | 200 |

| 3 | 300 |

+----+--------+

Output:

+---------------------+

| SecondHighestSalary |

+---------------------+

| 200 |

+---------------------+

Example 2:

Input:

Employee table:

+----+--------+

| id | salary |

+----+--------+

| 1 | 100 |
+----+--------+

Output:

+---------------------+

| SecondHighestSalary |

+---------------------+

| null |

+---------------------+

198. House Robber


You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from
robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken
into on the same night.

Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the
police.

Example 1:

Input: nums = [1,2,3,1]

Output: 4

Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).

Total amount you can rob = 1 + 3 = 4.

Example 2:

Input: nums = [2,7,9,3,1]

Output: 12

Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).

Total amount you can rob = 2 + 9 + 1 = 12.

Constraints:

 1 <= nums.length <= 100


 0 <= nums[i] <= 400

283. 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:

Input: nums = [0,1,0,3,12]

Output: [1,3,12,0,0]
Example 2:

Input: nums = [0]

Output: [0]

Constraints:

 1 <= nums.length <= 10 4

 -231
<= nums[i] <= 2
31
- 1

Follow up: Could you minimize the total number of operations done?

300. Longest Increasing Subsequence


Given an integer array nums, return the length of the longest strictly increasing subsequence.

Example 1:

Input: nums = [10,9,2,5,3,7,101,18]

Output: 4

Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.

Example 2:

Input: nums = [0,1,0,3,2,3]

Output: 4

Example 3:

Input: nums = [7,7,7,7,7,7,7]

Output: 1

Constraints:

 1 <= nums.length <= 2500


 -10 <= nums[i] <= 10
4 4

Follow up: Can you come up with an algorithm that runs in O(n log(n)) time complexity?

315. Count of Smaller Numbers After Self


Given an integer array nums, return an integer array counts where counts[i] is the number of smaller elements to the right of nums[i].

Example 1:
Input: nums = [5,2,6,1]

Output: [2,1,1,0]

Explanation:

To the right of 5 there are 2 smaller elements (2 and 1).

To the right of 2 there is only 1 smaller element (1).

To the right of 6 there is 1 smaller element (1).

To the right of 1 there is 0 smaller element.

Example 2:

Input: nums = [-1]

Output: [0]

Example 3:

Input: nums = [-1,-1]

Output: [0,0]

Constraints:

 1 <= nums.length <= 10 5

 -10 <= nums[i] <= 10


4 4

354. Russian Doll Envelopes


You are given a 2D array of integers envelopes where envelopes[i] = [w , h ] represents the width and the height of an envelope.
i i

One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height.

Return the maximum number of envelopes you can Russian doll (i.e., put one inside the other).

Note: You cannot rotate an envelope.

Example 1:

Input: envelopes = [[5,4],[6,4],[6,7],[2,3]]

Output: 3

Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).

Example 2:

Input: envelopes = [[1,1],[1,1],[1,1]]

Output: 1

Constraints:
 1 <= envelopes.length <= 10 5

 envelopes[i].length == 2
 1 <= w , h <= 10
i i
5

387. First Unique Character in a String


Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.

Example 1:

Input: s = "leetcode"

Output: 0

Example 2:

Input: s = "loveleetcode"

Output: 2

Example 3:

Input: s = "aabb"

Output: -1

Constraints:

 1 <= s.length <= 10 5

 s consists of only lowercase English letters.

416. Partition Equal Subset Sum


Given an integer array nums, return true if you can partition the array into two subsets such that the sum of the elements in both subsets is equal
or false otherwise.

Example 1:

Input: nums = [1,5,11,5]

Output: true

Explanation: The array can be partitioned as [1, 5, 5] and [11].

Example 2:

Input: nums = [1,2,3,5]

Output: false

Explanation: The array cannot be partitioned into equal sum subsets.

Constraints:

 1 <= nums.length <= 200


 1 <= nums[i] <= 100
540. Single Element in a Sorted Array
You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.

Return the single element that appears only once.

Your solution must run in O(log n) time and O(1) space.

Example 1:

Input: nums = [1,1,2,3,3,4,4,8,8]

Output: 2

Example 2:

Input: nums = [3,3,7,7,10,11,11]

Output: 10

Constraints:

 1 <= nums.length <= 10 5

 0 <= nums[i] <= 10 5

560. Subarray Sum Equals K


Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k.

A subarray is a contiguous non-empty sequence of elements within an array.

Example 1:

Input: nums = [1,1,1], k = 2

Output: 2

Example 2:

Input: nums = [1,2,3], k = 3

Output: 2

Constraints:

 1 <= nums.length <= 2 * 10 4

 -1000 <= nums[i] <= 1000


 -10 <= k <= 10
7 7

704. Binary Search


Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then
return its index. Otherwise, return -1.
You must write an algorithm with O(log n) runtime complexity.

Example 1:

Input: nums = [-1,0,3,5,9,12], target = 9

Output: 4

Explanation: 9 exists in nums and its index is 4

Example 2:

Input: nums = [-1,0,3,5,9,12], target = 2

Output: -1

Explanation: 2 does not exist in nums so return -1

Constraints:

 1 <= nums.length <= 10 4

 -10 < nums[i], target < 10


4 4

 All the integers in nums are unique.


 nums is sorted in ascending order.

856. Score of Parentheses


Given a balanced parentheses string s, return the score of the string.

The score of a balanced parentheses string is based on the following rule:

 "()" has score 1.


 AB has score A + B, where A and B are balanced parentheses strings.
 (A) has score 2 * A, where A is a balanced parentheses string.

Example 1:

Input: s = "()"

Output: 1

Example 2:

Input: s = "(())"

Output: 2

Example 3:

Input: s = "()()"

Output: 2

Constraints:
 2 <= s.length <= 50
 s consists of only '(' and ')'.
 s is a balanced parentheses string.

871. Minimum Number of Refueling Stops


A car travels from a starting position to a destination which is target miles east of the starting position.

There are gas stations along the way. The gas stations are represented as an array stations where stations[i] = [position , fuel ] indicates that
i i

the i gas station is position miles east of the starting position and has fuel liters of gas.
th
i i

The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses one liter of gas per one mile that it drives. When the car reaches a
gas station, it may stop and refuel, transferring all the gas from the station into the car.

Return the minimum number of refueling stops the car must make in order to reach its destination. If it cannot reach the destination, return -1.

Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have
arrived.

Example 1:

Input: target = 1, startFuel = 1, stations = []

Output: 0

Explanation: We can reach the target without refueling.

Example 2:

Input: target = 100, startFuel = 1, stations = [[10,100]]

Output: -1

Explanation: We can not reach the target (or even the first gas station).

Example 3:

Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]

Output: 2

Explanation: We start with 10 liters of fuel.

We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.

Then, we drive from position 10 to position 60 (expending 50 liters of fuel),

and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.

We made 2 refueling stops along the way, so we return 2.

Constraints:

 1 <= target, startFuel <= 10 9

 0 <= stations.length <= 500


 1 <= position < position
i i+1 < target
 1 <= fuel < 10i
9
941. Valid Mountain Array
Given an array of integers arr, return true if and only if it is a valid mountain array.

Recall that arr is a mountain array if and only if:

 arr.length >= 3
 There exists some i with 0 < i < arr.length - 1 such that:
o arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
o arr[i] > arr[i + 1] > ... > arr[arr.length - 1]

Example 1:

Input: arr = [2,1]

Output: false

Example 2:

Input: arr = [3,5,5]

Output: false

Example 3:

Input: arr = [0,3,2,1]

Output: true

Constraints:

 1 <= arr.length <= 10 4

 0 <= arr[i] <= 10 4


509. Fibonacci Number
The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones,
starting from 0 and 1. That is,

F(0) = 0, F(1) = 1

F(n) = F(n - 1) + F(n - 2), for n > 1.

Given n, calculate F(n).

Example 1:

Input: n = 2

Output: 1

Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.

Example 2:

Input: n = 3

Output: 2

Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.

Example 3:

Input: n = 4

Output: 3

Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.

Constraints:

 0 <= n <= 30

992. Subarrays with K Different Integers


Given an integer array nums and an integer k, return the number of good subarrays of nums.

A good array is an array where the number of different integers in that array is exactly k.

 For example, [1,2,3,1,2] has 3 different integers: 1, 2, and 3.

A subarray is a contiguous part of an array.

Example 1:

Input: nums = [1,2,1,2,3], k = 2

Output: 7

Explanation: Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2]

Example 2:
Input: nums = [1,2,1,3,4], k = 3

Output: 3

Explanation: Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4].

Constraints:

 1 <= nums.length <= 2 * 10 4

 1 <= nums[i], k <= nums.length

1010. Pairs of Songs With Total Durations Divisible by 60


You are given a list of songs where the i song has a duration of time[i] seconds.
th

Return the number of pairs of songs for which their total duration in seconds is divisible by 60. Formally, we want the number of indices i, j such that i <
j with (time[i] + time[j]) % 60 == 0.

Example 1:

Input: time = [30,20,150,100,40]

Output: 3

Explanation: Three pairs have a total duration divisible by 60:

(time[0] = 30, time[2] = 150): total duration 180

(time[1] = 20, time[3] = 100): total duration 120

(time[1] = 20, time[4] = 40): total duration 60

Example 2:

Input: time = [60,60,60]

Output: 3

Explanation: All three pairs have a total duration of 120, which is divisible by 60.

Constraints:

 1 <= time.length <= 6 * 10 4

 1 <= time[i] <= 500

1124. Longest Well-Performing Interval


We are given hours, a list of the number of hours worked per day for a given employee.

A day is considered to be a tiring day if and only if the number of hours worked is (strictly) greater than 8.

A well-performing interval is an interval of days for which the number of tiring days is strictly larger than the number of non-tiring days.

Return the length of the longest well-performing interval.


Example 1:

Input: hours = [9,9,6,0,6,6,9]

Output: 3

Explanation: The longest well-performing interval is [9,9,6].

Example 2:

Input: hours = [6,6,6]

Output: 0

Constraints:

 1 <= hours.length <= 10 4

 0 <= hours[i] <= 16

1356. Sort Integers by The Number of 1 Bits


You are given an integer array arr. Sort the integers in the array in ascending order by the number of 1's in their binary representation and in case of two or more
integers have the same number of 1's you have to sort them in ascending order.

Return the array after sorting it.

Example 1:

Input: arr = [0,1,2,3,4,5,6,7,8]

Output: [0,1,2,4,8,3,5,6,7]

Explantion: [0] is the only integer with 0 bits.

[1,2,4,8] all have 1 bit.

[3,5,6] have 2 bits.

[7] has 3 bits.

The sorted array by bits is [0,1,2,4,8,3,5,6,7]

Example 2:

Input: arr = [1024,512,256,128,64,32,16,8,4,2,1]

Output: [1,2,4,8,16,32,64,128,256,512,1024]

Explantion: All integers have 1 bit in the binary representation, you should just sort them in ascending order.

Constraints:

 1 <= arr.length <= 500


 0 <= arr[i] <= 10 4
1540. Can Convert String in K Moves
Given two strings s and t, your goal is to convert s into t in k moves or less.

During the i (1 <= i <= k) move you can:


th

 Choose any index j (1-indexed) from s, such that 1 <= j <= s.length and j has not been chosen in any previous move, and shift the character at
that index i times.
 Do nothing.

Shifting a character means replacing it by the next letter in the alphabet (wrapping around so that 'z' becomes 'a'). Shifting a character by i means applying the
shift operations i times.

Remember that any index j can be picked at most once.

Return true if it's possible to convert s into t in no more than k moves, otherwise return false.

Example 1:

Input: s = "input", t = "ouput", k = 9

Output: true

Explanation: In the 6th move, we shift 'i' 6 times to get 'o'. And in the 7th move we shift 'n' to get 'u'.

Example 2:

Input: s = "abc", t = "bcd", k = 10

Output: false

Explanation: We need to shift each character in s one time to convert it into t. We can shift 'a' to 'b' during the 1st move.
However, there is no way to shift the other characters in the remaining moves to obtain t from s.

Example 3:

Input: s = "aab", t = "bbb", k = 27

Output: true

Explanation: In the 1st move, we shift the first 'a' 1 time to get 'b'. In the 27th move, we shift the second 'a' 27 times to get
'b'.

Constraints:

 1 <= s.length, t.length <= 10^5


 0 <= k <= 10^9
 s, t contain only lowercase English letters.

1798. Maximum Number of Consecutive Values You Can Make


You are given an integer array coins of length n which represents the n coins that you own. The value of the i coin is coins[i]. You can make some value x if
th

you can choose some of your n coins such that their values sum up to x.

Return the maximum number of consecutive integer values that you can make with your coins starting from and including 0.

Note that you may have multiple coins of the same value.
Example 1:

Input: coins = [1,3]

Output: 2

Explanation: You can make the following values:

- 0: take []

- 1: take [1]

You can make 2 consecutive integer values starting from 0.

Example 2:

Input: coins = [1,1,1,4]

Output: 8

Explanation: You can make the following values:

- 0: take []

- 1: take [1]

- 2: take [1,1]

- 3: take [1,1,1]

- 4: take [4]

- 5: take [4,1]

- 6: take [4,1,1]

- 7: take [4,1,1,1]

You can make 8 consecutive integer values starting from 0.

Example 3:

Input: nums = [1,4,10,3,1]

Output: 20

Constraints:

 coins.length == n
 1 <= n <= 4 * 10 4

 1 <= coins[i] <= 4 * 10 4

1872. Stone Game VIII


Alice and Bob take turns playing a game, with Alice starting first.

There are n stones arranged in a row. On each player's turn, while the number of stones is more than one, they will do the following:

1. Choose an integer x > 1, and remove the leftmost x stones from the row.
2. Add the sum of the removed stones' values to the player's score.
3. Place a new stone, whose value is equal to that sum, on the left side of the row.
The game stops when only one stone is left in the row.

The score difference between Alice and Bob is (Alice's score - Bob's score). Alice's goal is to maximize the score difference, and Bob's goal is
the minimize the score difference.

Given an integer array stones of length n where stones[i] represents the value of the i stone from the left, return the score difference between Alice and
th

Bob if they both play optimally.

Example 1:

Input: stones = [-1,2,-3,4,-5]

Output: 5

Explanation:

- Alice removes the first 4 stones, adds (-1) + 2 + (-3) + 4 = 2 to her score, and places a stone of

value 2 on the left. stones = [2,-5].

- Bob removes the first 2 stones, adds 2 + (-5) = -3 to his score, and places a stone of value -3 on

the left. stones = [-3].

The difference between their scores is 2 - (-3) = 5.

Example 2:

Input: stones = [7,-6,5,10,5,-2,-6]

Output: 13

Explanation:

- Alice removes all stones, adds 7 + (-6) + 5 + 10 + 5 + (-2) + (-6) = 13 to her score, and places a

stone of value 13 on the left. stones = [13].

The difference between their scores is 13 - 0 = 13.

Example 3:

Input: stones = [-10,-12]

Output: -22

Explanation:

- Alice can only make one move, which is to remove both stones. She adds (-10) + (-12) = -22 to her

score and places a stone of value -22 on the left. stones = [-22].

The difference between their scores is (-22) - 0 = -22.

Constraints:

 n == stones.length
 2 <= n <= 10 5

 -10 <= stones[i] <= 10


4 4
1946. Largest Number After Mutating Substring
You are given a string num, which represents a large integer. You are also given a 0-indexed integer array change of length 10 that maps each digit 0-9 to
another digit. More formally, digit d maps to digit change[d].

You may choose to mutate a single substring of num. To mutate a substring, replace each digit num[i] with the digit it maps to in change (i.e.
replace num[i] with change[num[i]]).

Return a string representing the largest possible integer after mutating (or choosing not to) a single substring of num.

A substring is a contiguous sequence of characters within the string.

Example 1:

Input: num = "132", change = [9,8,5,0,3,6,4,2,6,8]

Output: "832"

Explanation: Replace the substring "1":

- 1 maps to change[1] = 8.

Thus, "132" becomes "832".

"832" is the largest number that can be created, so return it.

Example 2:

Input: num = "021", change = [9,4,3,5,7,2,1,9,0,6]

Output: "934"

Explanation: Replace the substring "021":

- 0 maps to change[0] = 9.

- 2 maps to change[2] = 3.

- 1 maps to change[1] = 4.

Thus, "021" becomes "934".

"934" is the largest number that can be created, so return it.

Example 3:

Input: num = "5", change = [1,4,7,5,3,2,5,6,9,4]

Output: "5"

Explanation: "5" is already the largest number that can be created, so return it.

Constraints:

 1 <= num.length <= 10 5

 num consists of only digits 0-9.


 change.length == 10
 0 <= change[d] <= 9
2035. Partition Array Into Two Arrays to Minimize Sum Difference
You are given an integer array nums of 2 * n integers. You need to partition nums into two arrays of length n to minimize the absolute difference of
the sums of the arrays. To partition nums, put each element of nums into one of the two arrays.

Return the minimum possible absolute difference.

Example 1:

Input: nums = [3,9,7,3]

Output: 2

Explanation: One optimal partition is: [3,9] and [7,3].

The absolute difference between the sums of the arrays is abs((3 + 9) - (7 + 3)) = 2.

Example 2:

Input: nums = [-36,36]

Output: 72

Explanation: One optimal partition is: [-36] and [36].

The absolute difference between the sums of the arrays is abs((-36) - (36)) = 72.

Example 3:

Input: nums = [2,-1,0,4,-2,-9]

Output: 0

Explanation: One optimal partition is: [2,4,-9] and [-1,0,-2].

The absolute difference between the sums of the arrays is abs((2 + 4 + -9) - (-1 + 0 + -2)) = 0.

Constraints:

 1 <= n <= 15
 nums.length == 2 * n
 -10 <= nums[i] <= 10
7 7
2233. Maximum Product After K Increments
You are given an array of non-negative integers nums and an integer k. In one operation, you may choose any element from nums and increment it by 1.

Return the maximum product of nums after at most k operations. Since the answer may be very large, return it modulo 10 + 7. Note that you should maximize
9

the product before taking the modulo.

Example 1:

Input: nums = [0,4], k = 5

Output: 20

Explanation: Increment the first number 5 times.

Now nums = [5, 4], with a product of 5 * 4 = 20.

It can be shown that 20 is maximum product possible, so we return 20.

Note that there may be other ways to increment nums to have the maximum product.

Example 2:

Input: nums = [6,3,3,2], k = 2

Output: 216

Explanation: Increment the second number 1 time and increment the fourth number 1 time.

Now nums = [6, 4, 3, 3], with a product of 6 * 4 * 3 * 3 = 216.

It can be shown that 216 is maximum product possible, so we return 216.

Note that there may be other ways to increment nums to have the maximum product.

Constraints:

 1 <= nums.length, k <= 10 5

 0 <= nums[i] <= 10 6

2338. Count the Number of Ideal Arrays


You are given two integers n and maxValue, which are used to describe an ideal array.

A 0-indexed integer array arr of length n is considered ideal if the following conditions hold:

 Every arr[i] is a value from 1 to maxValue, for 0 <= i < n.


 Every arr[i] is divisible by arr[i - 1], for 0 < i < n.

Return the number of distinct ideal arrays of length n. Since the answer may be very large, return it modulo 10 + 7.
9

Example 1:

Input: n = 2, maxValue = 5

Output: 10
Explanation: The following are the possible ideal arrays:

- Arrays starting with the value 1 (5 arrays): [1,1], [1,2], [1,3], [1,4], [1,5]

- Arrays starting with the value 2 (2 arrays): [2,2], [2,4]

- Arrays starting with the value 3 (1 array): [3,3]

- Arrays starting with the value 4 (1 array): [4,4]

- Arrays starting with the value 5 (1 array): [5,5]

There are a total of 5 + 2 + 1 + 1 + 1 = 10 distinct ideal arrays.

Example 2:

Input: n = 5, maxValue = 3

Output: 11

Explanation: The following are the possible ideal arrays:

- Arrays starting with the value 1 (9 arrays):

- With no other distinct values (1 array): [1,1,1,1,1]

- With 2 nd
distinct value 2 (4 arrays): [1,1,1,1,2], [1,1,1,2,2], [1,1,2,2,2], [1,2,2,2,2]

- With 2 nd
distinct value 3 (4 arrays): [1,1,1,1,3], [1,1,1,3,3], [1,1,3,3,3], [1,3,3,3,3]

- Arrays starting with the value 2 (1 array): [2,2,2,2,2]

- Arrays starting with the value 3 (1 array): [3,3,3,3,3]

There are a total of 9 + 1 + 1 = 11 distinct ideal arrays.

Constraints:

 2 <= n <= 10 4

 1 <= maxValue <= 10 4

2382. Maximum Segment Sum After Removals


You are given two 0-indexed integer arrays nums and removeQueries, both of length n. For the i query, the element in nums at the
th

index removeQueries[i] is removed, splitting nums into different segments.

A segment is a contiguous sequence of positive integers in nums. A segment sum is the sum of every element in a segment.

Return an integer array answer, of length n, where answer[i] is the maximum segment sum after applying the i removal.
th

Note: The same index will not be removed more than once.

Example 1:

Input: nums = [1,2,5,6,1], removeQueries = [0,3,2,4,1]

Output: [14,7,2,2,0]

Explanation: Using 0 to indicate a removed element, the answer is as follows:


Query 1: Remove the 0th element, nums becomes [0,2,5,6,1] and the maximum segment sum is 14 for segment [2,5,6,1].

Query 2: Remove the 3rd element, nums becomes [0,2,5,0,1] and the maximum segment sum is 7 for segment [2,5].

Query 3: Remove the 2nd element, nums becomes [0,2,0,0,1] and the maximum segment sum is 2 for segment [2].

Query 4: Remove the 4th element, nums becomes [0,2,0,0,0] and the maximum segment sum is 2 for segment [2].

Query 5: Remove the 1st element, nums becomes [0,0,0,0,0] and the maximum segment sum is 0, since there are no segments.

Finally, we return [14,7,2,2,0].

Example 2:

Input: nums = [3,2,11,1], removeQueries = [3,2,1,0]

Output: [16,5,3,0]

Explanation: Using 0 to indicate a removed element, the answer is as follows:

Query 1: Remove the 3rd element, nums becomes [3,2,11,0] and the maximum segment sum is 16 for segment [3,2,11].

Query 2: Remove the 2nd element, nums becomes [3,2,0,0] and the maximum segment sum is 5 for segment [3,2].

Query 3: Remove the 1st element, nums becomes [3,0,0,0] and the maximum segment sum is 3 for segment [3].

Query 4: Remove the 0th element, nums becomes [0,0,0,0] and the maximum segment sum is 0, since there are no segments.

Finally, we return [16,5,3,0].

Constraints:

 n == nums.length == removeQueries.length
 1 <= n <= 10 5

 1 <= nums[i] <= 10 9

 0 <= removeQueries[i] < n


 All the values of removeQueries are unique.

2418. Sort the People


You are given an array of strings names, and an array heights that consists of distinct positive integers. Both arrays are of length n.

For each index i, names[i] and heights[i] denote the name and height of the i person. th

Return names sorted in descending order by the people's heights.

Example 1:

Input: names = ["Mary","John","Emma"], heights = [180,165,170]

Output: ["Mary","Emma","John"]

Explanation: Mary is the tallest, followed by Emma and John.

Example 2:

Input: names = ["Alice","Bob","Bob"], heights = [155,185,150]

Output: ["Bob","Alice","Bob"]
Explanation: The first Bob is the tallest, followed by Alice and the second Bob.

Constraints:

 n == names.length == heights.length
 1 <= n <= 10 3

 1 <= names[i].length <= 20


 1 <= heights[i] <= 10 5

 names[i] consists of lower and upper case English letters.


 All the values of heights are distinct.

2457. Minimum Addition to Make Integer Beautiful


You are given two positive integers n and target.

An integer is considered beautiful if the sum of its digits is less than or equal to target.

Return the minimum non-negative integer x such that n + x is beautiful. The input will be generated such that it is always possible to make n beautiful.

Example 1:

Input: n = 16, target = 6

Output: 4

Explanation: Initially n is 16 and its digit sum is 1 + 6 = 7. After adding 4, n becomes 20 and digit sum becomes 2 + 0 = 2. It
can be shown that we can not make n beautiful with adding non-negative integer less than 4.

Example 2:

Input: n = 467, target = 6

Output: 33

Explanation: Initially n is 467 and its digit sum is 4 + 6 + 7 = 17. After adding 33, n becomes 500 and digit sum becomes 5 + 0 +
0 = 5. It can be shown that we can not make n beautiful with adding non-negative integer less than 33.

Example 3:

Input: n = 1, target = 1

Output: 0

Explanation: Initially n is 1 and its digit sum is 1, which is already smaller than or equal to target.

Constraints:

 1 <= n <= 10 12

 1 <= target <= 150


 The input will be generated such that it is always possible to make n beautiful.

2463. Minimum Total Distance Traveled


There are some robots and factories on the X-axis. You are given an integer array robot where robot[i] is the position of the i robot. You are also given a 2D
th

integer array factory where factory[j] = [position , limit ] indicates that position is the position of the j factory and that the j factory can
j j j
th th

repair at most limit robots.


j
The positions of each robot are unique. The positions of each factory are also unique. Note that a robot can be in the same position as a factory initially.

All the robots are initially broken; they keep moving in one direction. The direction could be the negative or the positive direction of the X-axis. When a robot
reaches a factory that did not reach its limit, the factory repairs the robot, and it stops moving.

At any moment, you can set the initial direction of moving for some robot. Your target is to minimize the total distance traveled by all the robots.

Return the minimum total distance traveled by all the robots. The test cases are generated such that all the robots can be repaired.

Note that

 All robots move at the same speed.


 If two robots move in the same direction, they will never collide.
 If two robots move in opposite directions and they meet at some point, they do not collide. They cross each other.
 If a robot passes by a factory that reached its limits, it crosses it as if it does not exist.
 If the robot moved from a position x to a position y, the distance it moved is |y - x|.

Example 1:

Input: robot = [0,4,6], factory = [[2,2],[6,2]]

Output: 4

Explanation: As shown in the figure:

- The first robot at position 0 moves in the positive direction. It will be repaired at the first factory.

- The second robot at position 4 moves in the negative direction. It will be repaired at the first factory.

- The third robot at position 6 will be repaired at the second factory. It does not need to move.

The limit of the first factory is 2, and it fixed 2 robots.

The limit of the second factory is 2, and it fixed 1 robot.

The total distance is |2 - 0| + |2 - 4| + |6 - 6| = 4. It can be shown that we cannot achieve a better total distance than 4.
Example 2:

Input: robot = [1,-1], factory = [[-2,1],[2,1]]

Output: 2

Explanation: As shown in the figure:

- The first robot at position 1 moves in the positive direction. It will be repaired at the second factory.

- The second robot at position -1 moves in the negative direction. It will be repaired at the first factory.

The limit of the first factory is 1, and it fixed 1 robot.

The limit of the second factory is 1, and it fixed 1 robot.

The total distance is |2 - 1| + |(-2) - (-1)| = 2. It can be shown that we cannot achieve a better total distance than 2.

Constraints:

 1 <= robot.length, factory.length <= 100


 factory[j].length == 2
 -10 <= robot[i], position <= 10
9
j
9

 0 <= limit <= robot.length


j

 The input will be generated such that it is always possible to repair every robot.

2445. Number of Nodes With Value One


There is an undirected connected tree with n nodes labeled from 1 to n and n - 1 edges. You are given the integer n. The parent node of a node with a label v is
the node with the label floor (v / 2). The root of the tree is the node with the label 1.

 For example, if n = 7, then the node with the label 3 has the node with the label floor(3 / 2) = 1 as its parent, and the node with the
label 7 has the node with the label floor(7 / 2) = 3 as its parent.

You are also given an integer array queries. Initially, every node has a value 0 on it. For each query queries[i], you should flip all values in the subtree of the
node with the label queries[i].

Return the total number of nodes with the value 1 after processing all the queries.
Note that:

 Flipping the value of a node means that the node with the value 0 becomes 1 and vice versa.
 floor(x) is equivalent to rounding x down to the nearest integer.

Example 1:

Input: n = 5 , queries = [1,2,5]

Output: 3

Explanation: The diagram above shows the tree structure and its status after performing the queries. The blue node represents the
value 0, and the red node represents the value 1.

After processing the queries, there are three red nodes (nodes with value 1): 1, 3, and 5.

Example 2:

Input: n = 3, queries = [2,3,3]

Output: 1

Explanation: The diagram above shows the tree structure and its status after performing the queries. The blue node represents the
value 0, and the red node represents the value 1.

After processing the queries, there are one red node (node with value 1): 2.

Constraints:
 1 <= n <= 10 5

 1 <= queries.length <= 10 5

 1 <= queries[i] <= n

2597. The Number of Beautiful Subsets


You are given an array nums of positive integers and a positive integer k.

A subset of nums is beautiful if it does not contain two integers with an absolute difference equal to k.

Return the number of non-empty beautiful subsets of the array nums.

A subset of nums is an array that can be obtained by deleting some (possibly none) elements from nums. Two subsets are different if and only if the chosen indices
to delete are different.

Example 1:

Input: nums = [2,4,6], k = 2

Output: 4

Explanation: The beautiful subsets of the array nums are: [2], [4], [6], [2, 6].

It can be proved that there are only 4 beautiful subsets in the array [2,4,6].

Example 2:

Input: nums = [1], k = 1

Output: 1

Explanation: The beautiful subset of the array nums is [1].

It can be proved that there is only 1 beautiful subset in the array [1].

Constraints:

 1 <= nums.length <= 20


 1 <= nums[i], k <= 1000

2612. Minimum Reverse Operations


You are given an integer n and an integer p in the range [0, n - 1]. Representing a 0-indexed array arr of length n where all positions are set to 0's, except
position p which is set to 1.

You are also given an integer array banned containing some positions from the array. For the ith position in banned, arr[banned[i]] = 0, and banned[i] !=
p.

You can perform multiple operations on arr. In an operation, you can choose a subarray with size k and reverse the subarray. However, the 1 in arr should
never go to any of the positions in banned. In other words, after each operation arr[banned[i]] remains 0.

Return an array ans where for each i from [0, n - 1], ans[i] is the minimum number of reverse operations needed to bring the 1 to position i in arr, or -1 if it
is impossible.

 A subarray is a contiguous non-empty sequence of elements within an array.


 The values of ans[i] are independent for all i's.
 The reverse of an array is an array containing the values in reverse order.
Example 1:

Input: n = 4, p = 0, banned = [1,2], k = 4

Output: [0,-1,-1,1]

Explanation: In this case k = 4 so there is only one possible reverse operation we can perform, which is reversing the whole
array. Initially, 1 is placed at position 0 so the amount of operations we need for position 0 is 0. We can never place a 1 on the
banned positions, so the answer for positions 1 and 2 is -1. Finally, with one reverse operation we can bring the 1 to index 3, so
the answer for position 3 is 1.

Example 2:

Input: n = 5, p = 0, banned = [2,4], k = 3

Output: [0,-1,-1,-1,-1]

Explanation: In this case the 1 is initially at position 0, so the answer for that position is 0. We can perform reverse
operations of size 3. The 1 is currently located at position 0, so we need to reverse the subarray [0, 2] for it to leave that
position, but reversing that subarray makes position 2 have a 1, which shouldn't happen. So, we can't move the 1 from position 0,
making the result for all the other positions -1.

Example 3:

Input: n = 4, p = 2, banned = [0,1,3], k = 1

Output: [-1,-1,0,-1]

Explanation: In this case we can only perform reverse operations of size 1. So the 1 never changes its position.

Constraints:

 1 <= n <= 10 5

 0 <= p <= n - 1
 0 <= banned.length <= n - 1
 0 <= banned[i] <= n - 1
 1 <= k <= n
 banned[i] != p
 all values in banned are unique

You might also like