[go: up one dir, main page]

0% found this document useful (0 votes)
11 views39 pages

Dsa

The document contains a series of coding problems from LeetCode, each with a description of the problem, input examples, and expected outputs. Problems range from finding the best time to buy and sell stock to identifying lucky numbers in a matrix. Each problem emphasizes the need for efficient algorithms and in-place modifications where applicable.

Uploaded by

Parn Jain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views39 pages

Dsa

The document contains a series of coding problems from LeetCode, each with a description of the problem, input examples, and expected outputs. Problems range from finding the best time to buy and sell stock to identifying lucky numbers in a matrix. Each problem emphasizes the need for efficient algorithms and in-place modifications where applicable.

Uploaded by

Parn Jain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

LeetCode

Q1. 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 i th 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 @
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.

Answer

Q2. 26. Remove Duplicates from Sorted Array

Given an integer array nuns 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.

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.
Custom Judge:

The judge will test your solution with the following code:

int[] nums = [...]; // Input array


int[] expectedNums = [...]; // The expected answer with correct
Length

Answer

Q3. 1480. Running Sum of 1d Array

Given an array nums. We define a running sum of an array as runningSum[i] =


um[nums[@]…nums[1]).

Return the running sum of nums.

Example 1:

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


Output: 1,3,6,10]
Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4] .

Example 2:

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

Output: 11,2,3,4,5]

Explanation: Running sum is obtained as follows: 11, 1+1, 1+1+1, 1+1+1+1,

1+1+1+1+1].

Answer
Q4. 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.

Answer

Q5. 977. Squares of a Sorted Array

Given an integer array nums sorted in non-decreasing order, return an array of the squares
of each number sorted in non-decreasing order.

Example 1:

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


Output: [0,1,9,16,100]
Explanation: After squaring, the array becomes [16,1,0,9,100].
After sorting, it becomes [0,1,9,16,100].

Example 2:

Input: nums = [-7,-3,2,3,11]


Output: [4,9,9,49,121]

Answer

Q6. 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.

Answer
Q7. 41. First Missing Positive

Given an unsorted integer array nums, return the smallest missing positive integer.

You must implement an algorithm that runs in O(n) time and uses constant extra space.

Example 1:

Input: nums = [1,2,0]


Output: 3
Explanation: The numbers in the range [1,2] are all in the array.

Example 2:

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


Output: 2
Explanation: 1 is in the array but 2 is missing.

Example 3:

Input: nums = [7,8,9,11,12]


Output: 1
Explanation: The smallest positive integer 1 is missing.

Answer

Q8. 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]

Answer

Q9. 169. 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:

Input: nums = [3,2,3]


Output: 3
Example 2:

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


Output: 2

Answer

Q10. 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]]

Answer
Q11. 724. Find Pivot Index

Given an array of integers nums, calculate the pivot index of this array.

The pivot index is the index where the sum of all the numbers strictly to the left of the index
is equal to the sum of all the numbers strictly to the index's right.

If the index is on the left edge of the array, then the left sum is 0 because there are no
elements to the left. This also applies to the right edge of the array.

Return the leftmost pivot index. If no such index exists, return -1.

Example 1:

Input: nums = [1,7,3,6,5,6]


Output: 3
Explanation:
The pivot index is 3.
Left sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11
Right sum = nums[4] + nums[5] = 5 + 6 = 11

Example 2:

Input: nums = [1,2,3]


Output: -1
Explanation:
There is no index that satisfies the conditions in the problem statement.

Example 3:
Input: nums = [2,1,-1]
Output: 0
Explanation:
The pivot index is 0.
Left sum = 0 (no elements to the left of index 0)
Right sum = nums[1] + nums[2] = 1 + -1 = 0

Answer

Q12. 287. Find the Duplicate Number

Given an array of integers nums containing n + 1 integers where each integer is in the range
[1, n] inclusive.

There is only one repeated number in nums, return this repeated number.

You must solve the problem without modifying the array nums and uses only constant extra
space.

Example 1:

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


Output: 2

Example 2:

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


Output: 3

Answer
Q13. 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.

Answer
Q14. 1010. Pairs of Songs With Total Durations Divisible by 60

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

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.

Answer

Q15. 238. 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:

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


Output: [24,12,8,6]

Example 2:

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


Output: [0,0,9,0,0]

Answer

Q16. 1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts

You are given a rectangular cake of size h x w and two arrays of integers horizontalCuts and
verticalCuts where:

horizontalCuts[i] is the distance from the top of the rectangular cake to the ith horizontal
cut and similarly, and

verticalCuts[j] is the distance from the left of the rectangular cake to the jth vertical cut.

Return the maximum area of a piece of cake after you cut at each horizontal and vertical
position provided in the arrays horizontalCuts and verticalCuts. Since the answer can be a
large number, return this modulo 109 + 7.
Example 1:

Input: h = 5, w = 4, horizontalCuts = [1,2,4], verticalCuts = [1,3]


Output: 4
Explanation: The figure above represents the given rectangular cake. Red lines are the
horizontal and vertical cuts. After you cut the cake, the green piece of cake has the
maximum area.

Example 2:

Input: h = 5, w = 4, horizontalCuts = [3,1], verticalCuts = [1]


Output: 6
Explanation: The figure above represents the given rectangular cake. Red lines are the
horizontal and vertical cuts. After you cut the cake, the green and yellow pieces of cake have
the maximum area.

Example 3:
Input: h = 5, w = 4, horizontalCuts = [3], verticalCuts = [3]
Output: 9
Answer
Q17. 2545. Sort the Students by Their Kth Score

There is a class with m students and n exams. You are given a 0-indexed m x n integer matrix
score, where each row represents one student and score[i][j] denotes the score the ith
student got in the jth exam. The matrix score contains distinct integers only.

You are also given an integer k. Sort the students (i.e., the rows of the matrix) by their
scores in the kth (0-indexed) exam from the highest to the lowest.

Return the matrix after sorting it.

Example 1:

Input: score = [[10,6,9,1],[7,5,11,2],[4,8,3,15]], k = 2


Output: [[7,5,11,2],[10,6,9,1],[4,8,3,15]]
Explanation: In the above diagram, S denotes the student, while E denotes the exam.
- The student with index 1 scored 11 in exam 2, which is the highest score, so they got first
place.
- The student with index 0 scored 9 in exam 2, which is the second highest score, so they got
second place.
- The student with index 2 scored 3 in exam 2, which is the lowest score, so they got third
place.
Example 2:

Input: score = [[3,4],[5,6]], k = 0


Output: [[5,6],[3,4]]
Explanation: In the above diagram, S denotes the student, while E denotes the exam.
- The student with index 1 scored 5 in exam 0, which is the highest score, so they got first
place.
- The student with index 0 scored 3 in exam 0, which is the lowest score, so they got second
place.

Answer

Q18. 1380. Lucky Numbers in a Matrix

Given an m x n matrix of distinct numbers, return all lucky numbers in the matrix in any
order.

A lucky number is an element of the matrix such that it is the minimum element in its row
and maximum in its column.

Example 1:

Input: matrix = [[3,7,8],[9,11,13],[15,16,17]]


Output: [15]
Explanation: 15 is the only lucky number since it is the minimum in its row and the
maximum in its column.
Example 2:

Input: matrix = [[1,10,4,2],[9,3,8,7],[15,16,17,12]]


Output: [12]
Explanation: 12 is the only lucky number since it is the minimum in its row and the
maximum in its column.

Example 3:

Input: matrix = [[7,8],[1,2]]


Output: [7]
Explanation: 7 is the only lucky number since it is the minimum in its row and the maximum
in its column.

Answer

Q19. 380. Insert Delete GetRandom O(1)

Implement the RandomizedSet class:

• RandomizedSet() Initializes the RandomizedSet object.


• bool insert(int val) Inserts an item val into the set if not present. Returns true if the
item was not present, false otherwise.
• bool remove(int val) Removes an item val from the set if present. Returns true if the
item was present, false otherwise.
• int getRandom() Returns a random element from the current set of elements (it's
guaranteed that at least one element exists when this method is called). Each
element must have the same probability of being returned.

You must implement the functions of the class such that each function works in average
O(1) time complexity.
Example 1:

Input
["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert",
"getRandom"]
[[], [1], [2], [2], [], [1], [2], []]
Output
[null, true, false, true, 2, true, false, 2]

Explanation
RandomizedSet randomizedSet = new RandomizedSet();
randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully.
randomizedSet.remove(2); // Returns false as 2 does not exist in the set.
randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2].
randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly.
randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2].
randomizedSet.insert(2); // 2 was already in the set, so return false.
randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will
always return 2.

Answer

Q20. 1876. Substrings of Size Three with Distinct Characters

A string is good if there are no repeated characters.

Given a string s, return the number of good substrings of length three in s.


Note that if there are multiple occurrences of the same substring, every occurrence should
be counted.

A substring is a contiguous sequence of characters in a string.

Example 1:

Input: s = "xyzzaz"
Output: 1
Explanation: There are 4 substrings of size 3: "xyz", "yzz", "zza", and "zaz".
The only good substring of length 3 is "xyz".

Example 2:

Input: s = "aababcabc"
Output: 4
Explanation: There are 7 substrings of size 3: "aab", "aba", "bab", "abc", "bca", "cab", and
"abc".
The good substrings are "abc", "bca", "cab", and "abc".

Answer

Q21. 763. Partition Labels

You are given a string s. We want to partition the string into as many parts as possible so
that each letter appears in at most one part.

Note that the partition is done so that after concatenating all the parts in order, the
resultant string should be s.

Return a list of integers representing the size of these parts.


Example 1:

Input: s = "ababcbacadefegdehijhklij"
Output: [9,7,8]
Explanation:
The partition is "ababcbaca", "defegde", "hijhklij".
This is a partition so that each letter appears in at most one part.
A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits s into less parts.

Example 2:

Input: s = "eccbbbbdec"
Output: [10]

Answer

Q22. 2161. Partition Array According to Given Pivot

You are given a 0-indexed integer array nums and an integer pivot. Rearrange nums such
that the following conditions are satisfied:

• Every element less than pivot appears before every element greater than pivot.
• Every element equal to pivot appears in between the elements less than and greater
than pivot.
• The relative order of the elements less than pivot and the elements greater than
pivot is maintained.
• More formally, consider every pi, pj where pi is the new position of the ith element
and pj is the new position of the jth element. For elements less than pivot, if i < j and
nums[i] < pivot and nums[j] < pivot, then pi < pj. Similarly for elements greater than
pivot, if i < j and nums[i] > pivot and nums[j] > pivot, then pi < pj.
Return nums after the rearrangement.
Example 1:

Input: nums = [9,12,5,10,14,3,10], pivot = 10


Output: [9,5,3,10,10,12,14]
Explanation:
The elements 9, 5, and 3 are less than the pivot so they are on the left side of the array.
The elements 12 and 14 are greater than the pivot so they are on the right side of the array.
The relative ordering of the elements less than and greater than pivot is also maintained. [9,
5, 3] and [12, 14] are the respective orderings.

Example 2:

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


Output: [-3,2,4,3]
Explanation:
The element -3 is less than the pivot so it is on the left side of the array.
The elements 4 and 3 are greater than the pivot so they are on the right side of the array.
The relative ordering of the elements less than and greater than pivot is also maintained. [-
3] and [4, 3] are the respective orderings.

Answer

Q23. 2442. Count Number of Distinct Integers After Reverse Operations

You are given an array nums consisting of positive integers.

You have to take each integer in the array, reverse its digits, and add it to the end of the
array. You should apply this operation to the original integers in nums.
vReturn the number of distinct integers in the final array.

Example 1:

Input: nums = [1,13,10,12,31]


Output: 6
Explanation: After including the reverse of each number, the resulting array is
[1,13,10,12,31,1,31,1,21,13].
The reversed integers that were added to the end of the array are underlined. Note that for
the integer 10, after reversing it, it becomes 01 which is just 1.
The number of distinct integers in this array is 6 (The numbers 1, 10, 12, 13, 21, and 31).

Example 2:

Input: nums = [2,2,2]


Output: 1
Explanation: After including the reverse of each number, the resulting array is [2,2,2,2,2,2].
The number of distinct integers in this array is 1 (The number 2).

Answer

Q24. 933. 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:

Input
["RecentCounter", "ping", "ping", "ping", "ping"]
[[], [1], [100], [3001], [3002]]
Output
[null, 1, 2, 3, 3]

Explanation
RecentCounter recentCounter = new RecentCounter();
recentCounter.ping(1); // requests = [1], range is [-2999,1], return 1
recentCounter.ping(100); // requests = [1, 100], range is [-2900,100], return 2
recentCounter.ping(3001); // requests = [1, 100, 3001], range is [1,3001], return 3
recentCounter.ping(3002); // requests = [1, 100, 3001, 3002], range is [2,3002], return 3

Answer

Q25. 2428. Maximum Sum of an Hourglass


You are given an m x n integer matrix grid.
We define an hourglass as a part of the matrix with the following form:
Return the maximum sum of the elements of an hourglass.

Note that an hourglass cannot be rotated and must be entirely contained within the matrix.

Example 1:

Input: grid = [[6,2,1,3],[4,2,1,5],[9,2,8,7],[4,1,2,9]]


Output: 30
Explanation: The cells shown above represent the hourglass with the maximum sum: 6 + 2 +
1 + 2 + 9 + 2 + 8 = 30.

Example 2:

Input: grid = [[1,2,3],[4,5,6],[7,8,9]]


Output: 35
Explanation: There is only one hourglass in the matrix, with the sum: 1 + 2 + 3 + 5 + 7 + 8 + 9
= 35.

Answer

Q26. 419. Battleships in a Board

iven an m x n matrix board where each cell is a battleship 'X' or empty '.', return the number
of the battleships on board.
Battleships can only be placed horizontally or vertically on board. In other words, they can
only be made of the shape 1 x k (1 row, k columns) or k x 1 (k rows, 1 column), where k can
be of any size. At least one horizontal or vertical cell separates between two battleships (i.e.,
there are no adjacent battleships).

Example 1:

Input: board = [["X",".",".","X"],[".",".",".","X"],[".",".",".","X"]]


Output: 2

Example 2:

Input: board = [["."]]


Output: 0

Answer

Q27. 1381. Design a Stack With Increment Operation

Design a stack that supports increment operations on its elements.

Implement the CustomStack class:

• CustomStack(int maxSize) Initializes the object with maxSize which is the maximum
number of elements in the stack.
• void push(int x) Adds x to the top of the stack if the stack has not reached the
maxSize.
• int pop() Pops and returns the top of the stack or -1 if the stack is empty.
• void inc(int k, int val) Increments the bottom k elements of the stack by val. If there
are less than k elements in the stack, increment all the elements in the stack.

Example 1:

Input
["CustomStack","push","push","pop","push","push","push","increment","increment","pop",
"pop","pop","pop"]
[[3],[1],[2],[],[2],[3],[4],[5,100],[2,100],[],[],[],[]]
Output
[null,null,null,2,null,null,null,null,null,103,202,201,-1]
Explanation
CustomStack stk = new CustomStack(3); // Stack is Empty []
stk.push(1); // stack becomes [1]
stk.push(2); // stack becomes [1, 2]
stk.pop(); // return 2 --> Return top of the stack 2, stack becomes [1]
stk.push(2); // stack becomes [1, 2]
stk.push(3); // stack becomes [1, 2, 3]
stk.push(4); // stack still [1, 2, 3], Do not add another elements as size is 4
stk.increment(5, 100); // stack becomes [101, 102, 103]
stk.increment(2, 100); // stack becomes [201, 202, 103]
stk.pop(); // return 103 --> Return top of the stack 103, stack becomes [201,
202]
stk.pop(); // return 202 --> Return top of the stack 202, stack becomes [201]
stk.pop(); // return 201 --> Return top of the stack 201, stack becomes []
stk.pop(); // return -1 --> Stack is empty return -1.

Answer
Q28. 442. Find All Duplicates in an Array

Given an integer array nums of length n where all the integers of nums are in the range [1,
n] and each integer appears once or twice, return an array of all the integers that appears
twice.

You must write an algorithm that runs in O(n) time and uses only constant extra space.

Example 1:

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


Output: [2,3]

Example 2:

Input: nums = [1,1,2]


Output: [1]

Example 3:

Input: nums = [1]


Output: []

Answer

Q29. 2405. Optimal Partition of String

Given a string s, partition the string into one or more substrings such that the characters in
each substring are unique. That is, no letter appears in a single substring more than once.
Return the minimum number of substrings in such a partition.

Note that each character should belong to exactly one substring in a partition.

Example 1:

Input: s = "abacaba"
Output: 4
Explanation:
Two possible partitions are ("a","ba","cab","a") and ("ab","a","ca","ba").
It can be shown that 4 is the minimum number of substrings needed.

Example 2:

Input: s = "ssssss"
Output: 6
Explanation:
The only valid partition is ("s","s","s","s","s","s").

Answer

Q30. 1780. Check if Number is a Sum of Powers of Three

Given an integer n, return true if it is possible to represent n as the sum of distinct powers of
three. Otherwise, return false.

An integer y is a power of three if there exists an integer x such that y == 3x.


Example 1:

Input: n = 12
Output: true
Explanation: 12 = 31 + 32

Example 2:

Input: n = 91
Output: true
Explanation: 91 = 30 + 32 + 34

Example 3:

Input: n = 21
Output: false

Answer

Q31. 2186. Minimum Number of Steps to Make Two Strings Anagram II

You are given two strings s and t. In one step, you can append any character to either s or t.

Return the minimum number of steps to make s and t anagrams of each other.

An anagram of a string is a string that contains the same characters with a different (or the
same) ordering.

Example 1:
Input: s = "leetcode", t = "coats"
Output: 7
Explanation:
- In 2 steps, we can append the letters in "as" onto s = "leetcode", forming s = "leetcodeas".
- In 5 steps, we can append the letters in "leede" onto t = "coats", forming t = "coatsleede".
"leetcodeas" and "coatsleede" are now anagrams of each other.
We used a total of 2 + 5 = 7 steps.
It can be shown that there is no way to make them anagrams of each other with less than 7
steps.

Example 2:

Input: s = "night", t = "thing"


Output: 0
Explanation: The given strings are already anagrams of each other. Thus, we do not need
any further steps.

Answer

Q32. 2317. Maximum XOR After Operations

You are given a 0-indexed integer array nums. In one operation, select any non-negative
integer x and an index i, then update nums[i] to be equal to nums[i] AND (nums[i] XOR x).

Note that AND is the bitwise AND operation and XOR is the bitwise XOR operation.

Return the maximum possible bitwise XOR of all elements of nums after applying the
operation any number of times.

Example 1:
Input: nums = [3,2,4,6]
Output: 7
Explanation: Apply the operation with x = 4 and i = 3, num[3] = 6 AND (6 XOR 4) = 6 AND 2 =
2.
Now, nums = [3, 2, 4, 2] and the bitwise XOR of all the elements = 3 XOR 2 XOR 4 XOR 2 = 7.
It can be shown that 7 is the maximum possible bitwise XOR.
Note that other operations may be used to achieve a bitwise XOR of 7.

Example 2:

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


Output: 11
Explanation: Apply the operation zero times.
The bitwise XOR of all the elements = 1 XOR 2 XOR 3 XOR 9 XOR 2 = 11.
It can be shown that 11 is the maximum possible bitwise XOR.

Answer

Q33. 1806. Minimum Number of Operations to Reinitialize a Permutation

You are given an even integer n. You initially have a permutation perm of size n where
perm[i] == i (0-indexed).

In one operation, you will create a new array arr, and for each i:

• If i % 2 == 0, then arr[i] = perm[i / 2].


• If i % 2 == 1, then arr[i] = perm[n / 2 + (i - 1) / 2].

You will then assign arr to perm.


Return the minimum non-zero number of operations you need to perform on perm to
return the permutation to its initial value.

Example 1:

Input: n = 2
Output: 1
Explanation: perm = [0,1] initially.
After the 1st operation, perm = [0,1]
So it takes only 1 operation.

Example 2:

Input: n = 4
Output: 2
Explanation: perm = [0,1,2,3] initially.
After the 1st operation, perm = [0,2,1,3]
After the 2nd operation, perm = [0,1,2,3]
So it takes only 2 operations.

Example 3:

Input: n = 6
Output: 4

Answer
Q34. 1630. Arithmetic Subarrays

A sequence of numbers is called arithmetic if it consists of at least two elements, and the
difference between every two consecutive elements is the same. More formally, a sequence
s is arithmetic if and only if s[i+1] - s[i] == s[1] - s[0] for all valid i.

For example, these are arithmetic sequences:

1, 3, 5, 7, 9
7, 7, 7, 7
3, -1, -5, -9

The following sequence is not arithmetic:

1, 1, 2, 5, 7
You are given an array of n integers, nums, and two arrays of m integers each, l and r,
representing the m range queries, where the ith query is the range [l[i], r[i]]. All the arrays
are 0-indexed.

Return a list of boolean elements answer, where answer[i] is true if the subarray nums[l[i]],
nums[l[i]+1], ... , nums[r[i]] can be rearranged to form an arithmetic sequence, and false
otherwise.

Example 1:

Input: nums = [4,6,5,9,3,7], l = [0,0,2], r = [2,3,5]


Output: [true,false,true]
Explanation:
In the 0th query, the subarray is [4,6,5]. This can be rearranged as [6,5,4], which is an
arithmetic sequence.
In the 1st query, the subarray is [4,6,5,9]. This cannot be rearranged as an arithmetic
sequence.
In the 2nd query, the subarray is [5,9,3,7]. This can be rearranged as [3,5,7,9], which is an
arithmetic sequence.

Example 2:

Input: nums = [-12,-9,-3,-12,-6,15,20,-25,-20,-15,-10], l = [0,1,6,4,8,7], r = [4,4,9,7,9,10]


Output: [false,true,false,false,true,true]

Answer

Q35. 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:
• arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
• 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

Answer

Q36. 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

Answer
Q37. 2043. Simple Bank System

You have been tasked with writing a program for a popular bank that will automate all its
incoming transactions (transfer, deposit, and withdraw). The bank has n accounts numbered
from 1 to n. The initial balance of each account is stored in a 0-indexed integer array
balance, with the (i + 1)th account having an initial balance of balance[i].

Execute all the valid transactions. A transaction is valid if:

• The given account number(s) are between 1 and n, and


• The amount of money withdrawn or transferred from is less than or equal to the
balance of the account.
Implement the Bank class:

• Bank(long[] balance) Initializes the object with the 0-indexed integer array balance.
• boolean transfer(int account1, int account2, long money) Transfers money dollars
from the account numbered account1 to the account numbered account2. Return
true if the transaction was successful, false otherwise.
• boolean deposit(int account, long money) Deposit money dollars into the account
numbered account. Return true if the transaction was successful, false otherwise.
• boolean withdraw(int account, long money) Withdraw money dollars from the
account numbered account. Return true if the transaction was successful, false
otherwise

Example 1:

Input
["Bank", "withdraw", "transfer", "deposit", "transfer", "withdraw"]
[[[10, 100, 20, 50, 30]], [3, 10], [5, 1, 20], [5, 20], [3, 4, 15], [10, 50]]
Output
[null, true, true, true, false, false]

Explanation
Bank bank = new Bank([10, 100, 20, 50, 30]);
bank.withdraw(3, 10); // return true, account 3 has a balance of $20, so it is valid to
withdraw $10.
// Account 3 has $20 - $10 = $10.
bank.transfer(5, 1, 20); // return true, account 5 has a balance of $30, so it is valid to
transfer $20.
// Account 5 has $30 - $20 = $10, and account 1 has $10 + $20 = $30.
bank.deposit(5, 20); // return true, it is valid to deposit $20 to account 5.
// Account 5 has $10 + $20 = $30.
bank.transfer(3, 4, 15); // return false, the current balance of account 3 is $10,
// so it is invalid to transfer $15 from it.
bank.withdraw(10, 50); // return false, it is invalid because account 10 does not exist.

Answer

Q38. 451. Sort Characters By Frequency

Given a string s, sort it in decreasing order based on the frequency of the characters. The
frequency of a character is the number of times it appears in the string.

Return the sorted string. If there are multiple answers, return any of them.

Example 1:

Input: s = "tree"
Output: "eert"
Explanation: 'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.

Example 2:
Input: s = "cccaaa"
Output: "aaaccc"
Explanation: Both 'c' and 'a' appear three times, so both "cccaaa" and "aaaccc" are valid
answers.
Note that "cacaca" is incorrect, as the same characters must be together.

Example 3:

Input: s = "Aabb"
Output: "bbAa"
Explanation: "bbaA" is also a valid answer, but "Aabb" is incorrect.
Note that 'A' and 'a' are treated as two different characters.

Answer

You might also like