Dsa
Dsa
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
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:
Answer
Example 1:
Example 2:
Output: 11,2,3,4,5]
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:
Example 2:
Example 3:
Answer
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:
Example 2:
Answer
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.
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:
Example 2:
Example 3:
Answer
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.
Example 1:
Example 2:
Example 3:
Answer
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:
Answer
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:
Example 2:
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
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:
Example 2:
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.
Example 1:
Example 2:
Example 3:
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:
Example 2:
Answer
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:
Example 2:
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:
Example 2:
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.
Example 1:
Answer
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:
Example 3:
Answer
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
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
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.
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
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:
Example 2:
Answer
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:
Example 2:
Answer
You have a RecentCounter class which counts the number of recent requests within a
certain time frame.
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
Note that an hourglass cannot be rotated and must be entirely contained within the matrix.
Example 1:
Example 2:
Answer
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:
Example 2:
Answer
• 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:
Example 2:
Example 3:
Answer
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
Given an integer n, return true if it is possible to represent n as the sum of distinct powers of
three. Otherwise, return false.
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
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:
Answer
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:
Answer
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:
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.
1, 3, 5, 7, 9
7, 7, 7, 7
3, -1, -5, -9
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:
Example 2:
Answer
Given an array of integers arr, return true if and only if it is a valid mountain array.
• 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
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.
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].
• 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
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