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

Leetcode questions imp

The document contains various Leetcode problems and their solutions, focusing on algorithms related to arrays, binary search, and mathematical computations. Key problems include finding the sum of two arrays, the maximum subarray, searching in a rotated sorted array, and determining the minimum ship capacity for shipping packages within a specified number of days. Each problem is accompanied by example inputs and outputs, along with the corresponding C++ code implementations.

Uploaded by

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

Leetcode questions imp

The document contains various Leetcode problems and their solutions, focusing on algorithms related to arrays, binary search, and mathematical computations. Key problems include finding the sum of two arrays, the maximum subarray, searching in a rotated sorted array, and determining the minimum ship capacity for shipping packages within a specified number of days. Each problem is accompanied by example inputs and outputs, along with the corresponding C++ code implementations.

Uploaded by

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

Leetcode questions imp

Arrays
Q-1 Sum of 2 arrays
Code
vector<int> findArraySum(vector<int>&a, int n, vector<int>&b, int m) {

vector<int> ans;
int sum = 0;
int carry = 0;
int i = n-1;
int j = m-1
while(i >= 0 && j >= 0){
int val1 = a[i];
int val2 = b[j];

sum = val1 + val2 + carry;


carry = sum / 10;
sum = sum % 10;
ans.push_back(sum);
i--;
j--;

}
while(i >= 0 || j >= 0 || carry!=0){
if(i >= 0){
int sum = a[i] + carry;
carry = sum/10;
sum = sum%10;
ans.push_back(sum);
i--;
}

else if(j >= 0){


int sum = b[j] + carry;
carry = sum/10;
sum = sum%10;
ans.push_back(sum);
j--;
}
else if(carry!=0){
int sum = carry;
carry = sum/10;
sum = sum%10;
ans.push_back(sum);
}
}
reverse(ans.begin(), ans.end());
return ans;
}
Q-253. Maximum Subarray Given an integer array nums, find the subarray with the
largest sum, and return its sum. Leetcode-53

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.
Code
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int sum=0;
int maxi=INT_MIN;
for(int i=0;i<nums.size();i++){
sum+=nums[i];
maxi=max(maxi,sum);

if(sum<0) sum=0;

}
return maxi;
}
};

Binary search
Q-1 Given an array of integers nums sorted in non-decreasing order, find the starting
and ending position of a given target value.

If target is not found in the array, return [-1, -1].

You must write an algorithm with O(log n) runtime complexity.

Example 1:

Input: nums = [5,7,7,8,8,10], target = 8


Output: [3,4]

Example 2:

Input: nums = [5,7,7,8,8,10], target = 6


Output: [-1,-1]

Example 3:

Input: nums = [], target = 0


Output: [-1,-1]

Code->

class Solution {
public:
vector<int> searchRange(vector<int>& arr, int target) {
//for first occurence
int lo=0;
int hi=arr.size()-1;
vector<int> v;
bool flag =true;
if(hi==0){
if(arr[hi]==target){
v.push_back(hi);
v.push_back(hi);
}
else{
v.push_back(-1);
v.push_back(-1);
}
}
else{

while(lo<=hi){
int mid=(lo+hi)/2;
if(arr[mid]==target){
if(mid==0){
flag=false;
v.push_back(mid);
break;
}
else if(arr[mid]==arr[mid-1]){
hi=mid-1;
}
else{
flag=false;
v.push_back(mid);
break;
}
}
else if(arr[mid]<target) lo=mid+1;
else hi=mid-1;
}
if(flag==true) v.push_back(-1);

//for last occurence


flag =true;
lo=0;
hi=arr.size()-1;
while(lo<=hi){
int mid=(lo+hi)/2;
if(arr[mid]==target){
if(mid==arr.size()-1){
flag=false;
v.push_back(mid);
break;
}
else if(arr[mid]==arr[mid+1]){
lo=mid+1;
}
else{
flag=false;
v.push_back(mid);
break;
}
}
else if(arr[mid]<target) lo=mid+1;
else hi=mid-1;
}
if(flag==true) v.push_back(-1);
}
return v;
}
};

Q-2 Given a non-negative integer x, return the square root of x rounded down to
the nearest integer. The returned integer should be non-negative as well.(square
root leetcode-69)

Code-

class Solution {
public:
long long int sqt(int n){
int s=0,e=n;
long long int mid=(s+e)/2;
int ans=-1;//for nearest integer square root
while (s<=e){
if(mid*mid==n) return mid; //why long long coz mid*mid may go
out of range
else if(mid*mid>n) e=mid-1;
else {s=mid+1; ans=mid;}
mid=(s+e)/2;
}
return ans;
}
int mySqrt(int x) {
return sqt(x);
}
};

Q-3Peak index in mountain array (leetcode -852

Code

class Solution {
public:
int peakIndexInMountainArray(vector<int>& arr) {
int s=0;
int e=arr.size()-1;
int mid=(s+e)/2;
while(s<=e){
mid=(s+e)/2;
if(arr[mid]>arr[mid+1] && arr[mid]>arr[mid-1]) return mid;
else if(arr[mid]>arr[mid+1]){
e=mid-1;
}
else{
s=mid+1;
}

}
return -1;
}
};
Q-4 Search in Rotated Sorted Array (leetcode- 33)

Code-

class Solution {
public:
int search(vector<int>& nums, int target) {
//1 3 4 5 6 8 20 28 33
//6 8 20 28 33 1 3 4 5
int n=nums.size();
//edge
if(n==2){
if(nums[0]==target) return 0;
else if(nums[1]==target) return 1;
else return -1;
}
int lo=0;
int hi=n-1;
int pivot=-1;
//finding pivot
while(lo<=hi){
int mid=lo+(hi-lo)/2;
if(mid==0) lo=mid+1; //for edge case--> [1,3] or [1]
else if(mid==n-1) hi=mid-1; //for edge case
else if(nums[mid]<nums[mid-1] && nums[mid]<nums[mid+1]){
pivot=mid;
break;
}
else if(nums[mid]>nums[mid-1] && nums[mid]>nums[mid+1]){
pivot=mid+1; //taking pivot as the smallest element
break;
}
else if(nums[mid]>nums[hi]) lo=mid+1;
else hi=mid-1;
}
if(pivot==-1){ //already sorted, no rotation
//normal binary search on full array
lo=0;
hi=n-1;
while(lo<=hi){
int mid=lo+(hi-lo)/2;
if(nums[mid]==target) return mid;
else if(nums[mid]>target) hi=mid-1;
else lo=mid+1;
}
return -1;

}
//finding the target
if(target>=nums[0] && target<=nums[pivot-1]){
lo=0;
hi=pivot-1;
while(lo<=hi){
int mid=lo+(hi-lo)/2;
if(nums[mid]==target) return mid;
else if(nums[mid]>target) hi=mid-1;
else lo=mid+1;
}
}
else{
lo=pivot;
hi=n-1;
while(lo<=hi){
int mid=lo+(hi-lo)/2;
if(nums[mid]==target) return mid;
else if(nums[mid]>target) hi=mid-1;
else lo=mid+1;
}
}
return -1;
}
};

Q-5 Find K closest elements( leetcode -658)

Given a sorted integer array arr, two integers k and x, return the k closest integers
to x in the array. The result should also be sorted in ascending order.

An integer a is closer to x than an integer b if:

 |a - x| < |b - x|, or
 |a - x| == |b - x| and a < b
 Example 1:
 Input: arr = [1,2,3,4,5], k = 4, x = 3
 Output: [1,2,3,4]
 Example 2:
 Input: arr = [1,2,3,4,5], k = 4, x = -1
 Output: [1,2,3,4]

Code

class Solution {
public:
vector<int> findClosestElements(vector<int>& arr, int k, int x) {
//S.C==0(k)

int n=arr.size();
vector<int> v;
if(x<arr[0]){
for(int i=0;i<k;i++){
v.emplace_back(arr[i]);
}
return v;
}
if(x>arr[n-1]){
for(int i=n-1;i>=n-k;i--){
v.emplace_back(arr[i]);
}
sort(v.begin(),v.end());
return v;
}
// if x is present in the array
int lo=0;
int hi=n-1;
bool flag=true; //if x is present or not
int lb,ub; //here lb and ub are indexes
while(lo<=hi){
int mid=lo+(hi-lo)/2;
if(arr[mid]==x) {
flag=false; //present
v.emplace_back(x);
lb=mid-1;
ub=mid+1;
break;
}
else if(arr[mid]>x){
hi=mid-1;
}
else lo=mid+1;
}
if(flag==true){
//lb and ub when x is not present
lb=hi;
ub=lo;
}
while(v.size()<k){
if(lb<0){
v.emplace_back(arr[ub]);
ub++;
}
else if(ub>n-1){
v.emplace_back(arr[lb]);
lb--;
}
else{
int e1=arr[lb]-x;
int e2=arr[ub]-x;
if(e1<0) e1*=-1;
if(e2<0) e2*=-1;
if(e1<=e2) {
v.emplace_back(arr[lb]);
lb--;
}
else{
v.emplace_back(arr[ub]);
ub++;
}
}
}
sort(v.begin(),v.end());
return v;

}
};

Q-6 Sum of square numbers (leetcode-633)


Given a non-negative integer c, decide whether there're two integers a and b such
that
a^2 +b^2= c.

code

class Solution {
public:
bool isPerfectSquare(int n){
int root=sqrt(n);
if(root*root==n) return true;
else return false;
}
bool judgeSquareSum(int c) {
//method-1
// int x=0;
// int y=c;
// while(x<=y){
// if(isPerfectSquare(x) && isPerfectSquare(y)){
// return true;
// }
// x++;y--;
// }

//method2
int x=0;
int y=c;
while(x<=y){
if(isPerfectSquare(x) && isPerfectSquare(y)){
return true;
}
else if(!isPerfectSquare(y)){
y=(int)sqrt(y)*(int)sqrt(y);
x=c-y;
}
else{
x=(int)(sqrt(x)+1)*(int)(sqrt(x)+1);
y=c-x;
}
}
return false;
}
};

Q-7 Capacity to ship packages within D days(leetcode-1011)

A conveyor belt has packages that must be shipped from one port to another
within days days.

The i package on the conveyor belt has a weight of weights[i]. Each day, we load the
th

ship with packages on the conveyor belt (in the order given by weights). We may not
load more weight than the maximum weight capacity of the ship.

Return the least weight capacity of the ship that will result in all the packages on the
conveyor belt being shipped within days days.

Example 1:

Input: weights = [1,2,3,4,5,6,7,8,9,10], days = 5


Output: 15
Explanation: A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:
1st day: 1, 2, 3, 4, 5
2nd day: 6, 7
3rd day: 8
4th day: 9
5th day: 10

Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and
splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed.

Example 2:

Input: weights = [3,2,2,4,1,4], days = 3


Output: 6
Explanation: A ship capacity of 6 is the minimum to ship all the packages in 3 days like this:
1st day: 3, 2
2nd day: 2, 4
3rd day: 1, 4

Code

class Solution {
public:
bool check(int mid,vector<int> weights,int days){
//3,2,2,4,1,4 days=3
int n=weights.size();
int m=mid;
int count=0;
for(int i=0;i<n;i++){
if(m>=weights[i]){
m-=weights[i];
}
else{
count++;
m=mid;
m-=weights[i];
}
}
count++;
if(count>days) return false;
else return true;
}
int shipWithinDays(vector<int>& weights, int days) {
int n=weights.size();
int max=INT_MIN;
int sum=0;
for(int i=0;i<n;i++){
if(max<weights[i]) max=weight[i];
sum+=weights[i];
}
int lo=max;
int hi=sum;
int ans=sum;
while(lo<=hi){
int mid=lo+()hi-lo)/2;
if(check(mid,weights,days)){
ans=mid;
hi=mid-1;
}
else lo=mid+1;
}
return ans;
}
};
Q-8 Koko eating bananas (leetcode-875)

Koko loves to eat bananas. There are n piles of bananas, the i pile
th

has piles[i] bananas. The guards have gone and will come back in h hours.

Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses
some pile of bananas and eats k bananas from that pile. If the pile has less
than k bananas, she eats all of them instead and will not eat any more bananas
during this hour.

Koko likes to eat slowly but still wants to finish eating all the bananas before the
guards return.

Return the minimum integer k such that she can eat all the bananas within h hours.

Example 1:

Input: piles = [3,6,7,11], h = 8


Output: 4

Example 2:

Input: piles = [30,11,23,4,20], h = 5


Output: 30

Example 3:

Input: piles = [30,11,23,4,20], h = 6


Output: 23

Code

class Solution {
public:
bool check(int mid,vector<int>& piles, int h){ //mid=speed
long long count=0; //lon long coz in some cases count is excceding
the range of int
int n=piles.size();
for(int i=0;i<n;i++){
long long hr;
if(piles[i]%mid==0){
hr=(long long)piles[i]/mid;
}
else hr=(long long)piles[i]/mid+1;
count+=hr;
}
if(count>h) return false;
else return true;
}
int minEatingSpeed(vector<int>& piles, int h) {
int n=piles.size();
int mx=-1;
for(int i=0;i<n;i++){
if(mx<piles[i]) mx=piles[i];
}
int lo=1;
int hi=mx;
int ans=hi;
while(lo<=hi){
int mid=lo+(hi-lo)/2;
if(check(mid,piles,h)){
ans=mid;
hi=mid-1;
}
else{
lo=mid+1;
}
}
return ans;
}
};

Q-9 Minimum time to complete trips

You are given an array time where time[i] denotes the time taken by the i bus to
th

complete one trip.

Each bus can make multiple trips successively; that is, the next trip can
start immediately after completing the current trip. Also, each bus
operates independently; that is, the trips of one bus do not influence the trips of
any other bus.

You are also given an integer totalTrips, which denotes the number of trips all buses
should make in total. Return the minimum time required for all buses to
complete at least totalTrips trips.

Example 1:

Input: time = [1,2,3], totalTrips = 5


Output: 3
Explanation:
- At time t = 1, the number of trips completed by each bus are [1,0,0].
The total number of trips completed is 1 + 0 + 0 = 1.
- At time t = 2, the number of trips completed by each bus are [2,1,0].
The total number of trips completed is 2 + 1 + 0 = 3.
- At time t = 3, the number of trips completed by each bus are [3,1,1].
The total number of trips completed is 3 + 1 + 1 = 5.
So the minimum time needed for all buses to complete at least 5 trips is 3.

Code

class Solution {
public:
bool check(long long t,vector<int>& time, int totalTrips){
long long trips=0;
int n=time.size();
for(int i=0;i<n;i++){
// if(t%time[i]==0){
trips+=t/(long long)time[i];
// }
// else{
// trips+=(t/time[i]+1);
// }
}
if(trips>=(long long)totalTrips) return true;
else return false;
}
long long minimumTime(vector<int>& time, int totalTrips) {
//3 3 3 tt=5
//after 3hr [1 1 1]=3 but <tt
//after 6hr [2 2 2] =6
// hi=max*tt
int n=time.size();
long long min=INT_MAX;
long long max=INT_MIN;
for(int i=0;i<n;i++){
if(min>(long long)time[i]) min=(long long)time[i];
if(max<(long long)time[i]) max=(long long)time[i];
}
long long lo=min;
long long hi=max*totalTrips;
long long ans=max;
while(lo<=hi){
long long mid=lo+(hi-lo)/2;
if(check(mid,time,totalTrips)){
ans=mid;
hi=mid-1;
}
else lo=mid+1;
}
return ans;
}
};

Q-10-Arranging coins (leetcode-441)

You have n coins and you want to build a staircase with these coins. The staircase
consists of k rows where the i row has exactly i coins. The last row of the
th

staircase may be incomplete.

Given the integer n, return the number of complete rows of the staircase you will
build.

Input: n = 5
Output: 2
Explanation: Because the 3rd row is incomplete, we return 2.

Code

class Solution {
public:
bool IsTrue(int m,int n){
long long condition=(long long)m*((long long)m+1)/2;
if(condition<=(long long)n) return true;
else return false;

}
int arrangeCoins(int n) {
int lo=0;
int hi=n;
int ans;
while(lo<=hi){
int mid=lo+(hi-lo)/2;
if(IsTrue(mid,n)){
ans=mid;
lo=mid+1;
}
else hi=mid-1;
}
return ans;
}
};

Q-11 Searching a 2D array

You are given an m x n integer matrix matrix with the following two properties:

 Each row is sorted in non-decreasing order.


 The first integer of each row is greater than the last integer of the previous
row.

Given an integer target, return true if target is in matrix or false otherwise.

You must write a solution in O(log(m * n)) time complexity.

Code

class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
//T.C=O(m.log(n))
// int flag=false;
// int nr=matrix.size();
// int nc=matrix[0].size();
// for(int i=0;i<nr;i++){
// int lo=0;
// int hi=nc-1;
// while(lo<=hi){
// int mid=lo+(hi-lo)/2;
// if(matrix[i][mid]==target){
// flag=true;
// break;
// }
// else if(matrix[i][mid]<target){
// lo=mid+1;
// }
// else hi=mid-1;
// }
// if(flag==true) return true;
// }
// return flag;
// return 0;

//T.C=O(log(m.n))
int flag=false;
int nr=matrix.size();
int nc=matrix[0].size();
int lo=0;
int hi=nr*nc-1;
while(lo<=hi){
int mid=lo+(hi-lo)/2;
int r=mid/nc,c=mid%nc;
if(matrix[r][c]==target){
flag=true;
break;
}
else if(matrix[r][c]<target){
lo=mid+1;
}
else hi=mid-1;
}
return flag;
}
};

Q-12 Search in rotated sorted array II (leetcode-81)

In this duplicate elements are allowed which were not in leetcode-33(Search in rotated sorted array
I)

Code

class Solution {
public:
bool search(vector<int>& arr, int target) {
int n=arr.size();
int lo=0;
int hi=n-1;
while(lo<=hi){
int mid=lo+(hi-lo)/2;
if(arr[mid]==target) return true;
//extra cond for repetetive elements array vala case error
else if(arr[lo]==arr[mid] && arr[mid]==arr[hi]){
hi--; lo++;
}
else if(arr[mid]<=arr[hi]){ //is the mid-hi sorted
if(target>=arr[mid] && target<=arr[hi]) lo=mid+1;
else hi=mid-1;
}
else{ //arr[lo]<=arr[mid] that is lo-mid is sorted
if(target>=arr[lo] && target<=arr[mid]) hi=mid-1;
else lo=mid+1;
}
}
return false;
}
};

This code will work both for 33 and 81!!!

Recursion
Q-1 Number of steps to reduce a number to zero {leet code-1342}

Given an integer num, return the number of steps to reduce it to zero.

In one step, if the current number is even, you have to divide it by 2, otherwise, you
have to subtract 1 from it.

Example 1:

Input: num = 14
Output: 6
Explanation:
Step 1) 14 is even; divide by 2 and obtain 7.
Step 2) 7 is odd; subtract 1 and obtain 6.
Step 3) 6 is even; divide by 2 and obtain 3.
Step 4) 3 is odd; subtract 1 and obtain 2.
Step 5) 2 is even; divide by 2 and obtain 1.
Step 6) 1 is odd; subtract 1 and obtain 0.

Code

class Solution {
public:
int numberOfSteps(int n) { // by recursion
if(n==0) return 0;
if(n%2==0) return (1+numberOfSteps(n/2));
else return (1+numberOfSteps(n-1));
}
};

Q-2Combination sum

Given an array of distinct integers candidates and a target integer target, return a list
of all unique combinations of candidates where the chosen numbers sum
to target. You may return the combinations in any order.

The same number may be chosen from candidates an unlimited number of times.
Two combinations are unique if the

frequency
of at least one of the chosen numbers is different.

The test cases are generated such that the number of unique combinations that sum
up to target is less than 150 combinations for the given input.

Example 1:

Input: candidates = [2,3,6,7], target = 7


Output: [[2,2,3],[7]]
Explanation:
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two combinations.

Code

class Solution {
public:
void combination(vector<vector<int>>&ans,vector<int> v,vector<int>&
candidates,int target,int idx){
if(target==0){
ans.push_back(v);
}
if(target<0) return;
for(int i=idx;i<candidates.size();i++){
v.push_back(candidates[i]);
combination(ans,v,candidates,target-candidates[i],i);
v.pop_back(); // backtracking concept but ussi vector me add na ho
alag vector bane isliye kiya h pop coz we want [2], not[2,3...]
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target)
{
vector<vector<int>> ans;
vector<int> v;
combination(ans,v,candidates,target,0);
return ans;
}
};

Advance Sorting
Q-1Missing number (leetcode-268)

Given an array nums containing n distinct numbers in the range [0, n], return the only
number in the range that is missing from the array.

Example 1:

Input: nums = [3,0,1]


Output: 2
Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the
missing number in the range since it does not appear in nums.

Code

class Solution {
public:
int missingNumber(vector<int>& nums) {
int n=nums.size();
// vector<int> check(n+1,0);
// for(int i=0;i<n;i++){
// check[nums[i]]=1;
// }
// int ans;
// for(int i=0;i<n+1;i++){
// if(check[i]==0){
// ans= i;
// break;
// }
// }
// return ans;
//method-2 cyclic sort
// int i=0;
// while(i<n){
// if(nums[i]==n) i++;
// else if(nums[i]!=i) swap(nums[i],nums[nums[i]]);
// else i++;
// }
// int ans;
// for(int i=0;i<n;i++){
// if(nums[i]!=i){
// return i;
// }
// }
// return n;
//method-3 sum method
int s=0;
for(int i=0;i<n;i++){
s+=nums[i];
}
int actual_sum=n*(n+1)/2;
return actual_sum-s;

}
};

Q-2Find the duplicate numbers

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.

Example 1:

Input: nums = [

Code

class Solution {
public:
int findDuplicate(vector<int>& arr) {
//method-1 sum-method
//method-2 special array
//method-3 cyclic sort
int i=0;
int n=arr.size();
int ans;
while(i<n){
if(arr[i]!=i+1){
if(arr[i]==arr[arr[i]-1]) {
ans=arr[i];
break;
}
else swap(arr[i],arr[arr[i]-1]);
}
else i++;
}
return ans;
}
};

Q-3 Find all the numbers disappeared in an array(leetcode-448)

Given an array nums of n integers where nums[i] is in the range [1, n], return an array
of all the integers in the range [1, n] that do not appear in nums.

Example 1:

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


Output: [5,6]

Code

class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
//method-1 by special array method
//method-2 acc to condn of follow up question
vector<int> v;
int i=0;
while(i<nums.size()){
if(nums[i]!=i+1){
if(nums[i]==nums[nums[i]-1]) i++;
else swap(nums[i],nums[nums[i]-1]);
}
else i++;
}
for(int i=0;i<nums.size();i++){
if(nums[i]!=i+1) v.push_back(i+1);
}
return v;

}
};
Q-4 First missing positive number (leetcode number-41)

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 O(1) auxiliary
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.

Code

class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
int n=nums.size();
int i=0;
while(i<n){
if (nums[i]<=0) i++;
else if(nums[i]>n) i++;
else if(nums[i]!=i+1){
if(nums[i]==nums[nums[i]-1]) i++;
else swap(nums[i],nums[nums[i]-1]);
}
else i++;
}
int ans;
for(int i=0;i<n;i++){
if(nums[i]!=i+1){
return i+1;
break;
}
}
return n+1;
}
};

Q-5 Reverse Pair (leetcode no-493)

(exactly same logic as of inversion count-merge sort)

Given an integer array nums, return the number of reverse pairs in the array.

A reverse pair is a pair (i, j) where:

 0 <= i < j < nums.length and


 nums[i] > 2 * nums[j].

Example 1:

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


Output: 2
Explanation: The reverse pairs are:
(1, 4) --> nums[1] = 3, nums[4] = 1, 3 > 2 * 1
(3, 4) --> nums[3] = 3, nums[4] = 1, 3 > 2 * 1

Example 2:

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


Output: 3
Explanation: The reverse pairs are:
(1, 4) --> nums[1] = 4, nums[4] = 1, 4 > 2 * 1
(2, 4) --> nums[2] = 3, nums[4] = 1, 3 > 2 * 1
(3, 4) --> nums[3] = 5, nums[4] = 1, 5 > 2 * 1
Example -3
nums =[1,2,3,4,5]
Output
0
Code

class Solution {
public:
long long count=0;
long long revPair(vector<int> a,vector<int> b){
long long i=0; //i for a
long long j=0; //j for b
long long c=0;
while(i<a.size() && j<b.size()){

// if(a[i]>b[j]){
// if(a[i]>2*b[j]){
// c+=a.size()-i;
// j++;
// }
// else{
// i++;
// }
// }
// else if( a[i]<b[j]){
// if(a[i]*2<b[j]){
// c+=b.size()-j;
// i++;
// }
// else{
// j++;
// }

// }
// else if( a[i]==b[j]){
// i++; j++;
// }
if((long long)a[i]>(long long)2*b[j]){

c+=a.size()-i;
j++;

}
else{
i++;
}
// else if( a[i]<b[j]){
// i++;
// }
// else if( a[i]==b[j]){
// if(b[j]<0){
// c+=a.size()-i;
// j++;
// }
// else i++;
// }
}
return c;
}
void merge(vector<int> &n,vector<int> &m,vector<int> &v){
int i=0;//for n
int j=0;//for m
int m1=m.size();
int n1=n.size();

for(int k=0;k<(m1+n1);k++){
if(i>=n.size()) {v[k]=m[j]; j++;}
else if(j>=m.size()) {v[k]=n[i]; i++;}
else if(n[i]<=m[j]) {v[k]=n[i]; i++;}
else if(m[j]<n[i]) {v[k]=m[j]; j++;}
}
}
void mergeSort(vector<int>& v){
int n=v.size();
if(n==1) return;
int n1=n/2,n2=n-n/2;
vector<int> a(n1),b(n2);
//copy pasting
for(int i=0;i<n1;i++){
a[i]=v[i];
}
for(int i=0;i<n2;i++){
b[i]=v[i+n1];
}
//magic-Recursion
mergeSort(a);
mergeSort(b);
//count function for reverse pair-->
count+=revPair(a,b);
//merging the 2 arrays
merge(a,b,v);
a.clear();
b.clear();
}
int reversePairs(vector<int>& v) {
mergeSort(v);
return count;
}
};

Q- Cyclic sort pe

Q-1 Set Mismatch (leetcode-645)

You have a set of integers s, which originally contains all the numbers from 1 to n.
Unfortunately, due to some error, one of the numbers in s got duplicated to another
number in the set, which results in repetition of one number and loss of
another number.

You are given an integer array nums representing the data status of this set after the
error.

Find the number that occurs twice and the number that is missing and return them
in the form of an array.

Example 1:

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


Output: [2,3]

Example 2:

Input: nums = [1,1]


Output: [1,2]

Code

class Solution {
public:
vector<int> findErrorNums(vector<int>& nums) {
vector<int> ans;
int n=nums.size();
int i=0;
while(i<n){
if(nums[i]!=i+1){
if(nums[i]==nums[nums[i]-1]) i++;
else swap(nums[i],nums[nums[i]-1]);
}
else i++;
}
//now checking the duplicate and the missing number
for(int i=0;i<n;i++){
if(nums[i]!=i+1){
ans.emplace_back(nums[i]);
ans.emplace_back(i+1);
break;
}
}
return ans;
}
};

Q-2 Find All duplicates in the array (leetcode-442)

Code

class Solution {
public:
vector<int> findDuplicates(vector<int>& nums) {
int n=nums.size();
vector<int> ans;
int i=0;
while(i<n){
if(nums[i]!=i+1){
if(nums[i]==nums[nums[i]-1]) i++;
else swap(nums[i],nums[nums[i]-1]);
}
else i++;
}
for(int i=0;i<n;i++){
if(nums[i]!=i+1) ans.emplace_back(nums[i]);
}
return ans;
}
};

Advance algorithm
Prefix and suffix sum and product
Q-1 Product of array except itself (L.C.- 238)

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

Code

class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
//method-1 find profuct of whole array then ans[i]=product/arr[i]
//method-2 use of prefic and suffix product
int n=nums.size();
// vector<int> prep(n); vector<int> sufp(n);
// //making prefix product
// for(int i=0;i<n;i++){
// if(i==0) prep[i]=nums[i];
// else prep[i]=nums[i]*prep[i-1];
// }
// //making suffix product
// for(int i=n-1;i>=0;i--){
// if(i==n-1) sufp[i]=nums[i];
// else sufp[i]=nums[i]*sufp[i+1];
// }
// vector<int> v(n);
// for(int i=0;i<n;i++){
// if(i==0) v[i]=sufp[i+1];
// else if( i==n-1) v[i]=prep[i-1];
// else v[i]=prep[i-1]*sufp[i+1];
// }
// return v;
// method-3(sir's way)
vector<int> pre(n);
vector<int> suf(n);
vector<int> ans(n);
// prefix product array
int p=nums[0];
pre[0]=1;
for(int i=i;i<n;i++){
pre[i]=p;
p*=num[i];
}
//suffix product array
p=nums[n-1];
suf[n-1]=1;
for(int i=n-2;i>=0;i--){
suf[i]=p;
p*=nums[i];
}
//ans array
for(int i=0;i<n;i++){
ans[i]=pre[i]*suf[i];
}
return ans;
}
};

Q-2Minimum Penalty for a shop (Leetcode number-2483)

You are given the customer visit log of a shop represented by a 0-


indexed string customers consisting only of characters 'N' and 'Y':

 if the i character is 'Y', it means that customers come at the i hour


th th

 whereas 'N' indicates that no customers come at the i hour.


th

If the shop closes at the j hour (0 <= j <= n), the penalty is calculated as follows:
th

 For every hour when the shop is open and no customers come, the penalty
increases by 1.
 For every hour when the shop is closed and customers come, the penalty
increases by 1.

Return the earliest hour at which the shop must be closed to incur
a minimum penalty.

Note that if a shop closes at the j hour, it means the shop is closed at the hour j.
th

Example-1

Input: customers = "YYNY"


Output: 2
Explanation:
- Closing the shop at the 0 th hour incurs in 1+1+0+1 = 3 penalty.
- Closing the shop at the 1 st hour incurs in 0+1+0+1 = 2 penalty.
- Closing the shop at the 2 nd hour incurs in 0+0+0+1 = 1 penalty.
- Closing the shop at the 3 rd hour incurs in 0+0+1+1 = 2 penalty.
- Closing the shop at the 4 th hour incurs in 0+0+1+0 = 1 penalty.
Closing the shop at 2 nd or 4th hour gives a minimum penalty. Since 2 is earlier, the optimal closing
time is 2.

Example 2:

Input: customers = "NNNNN"


Output: 0
Explanation: It is best to close the shop at the 0 th hour as no customers arrive.

Example 3:

Input: customers = "YYYY"


Output: 4
Explanation: It is best to close the shop at the 4 th hour as customers arrive at each hour.

Code

class Solution {
public:
int bestClosingTime(string s) {
// vector<int> v;
// for(int i=0;i<=s.length();i++){
// int c=0;
// for(int j=0;j<i;j++){
// if(s[j]=='Y') c++;
// }
// for(int k=i;k<s.length();k++){
// if(s[k]=='N') c++;
// }
// v.emplace_back(c);
// }
// int min=-1; int idx=-1;
// for(int i=0;i<v.size();i++){
// if(min<v[i]){
// min=v[i];
// idx=i;
// }
// }
// return idx;

// method-2 using prefix and suffix sum

int n=s.length();
vector<int> pre(n+1); //no of N before the kth hour
vector<int> suf(n+1); //no of Y after and including the kth hour
pre[0]=0;
for(int i=1;i<n+1;i++){
if(s[i-1]=='N') pre[i]=pre[i-1]+1;
else pre[i]=pre[i-1];
}
//for suffix
suf[n]=0;
for(int i=n-1;i>=0;i--){
if(s[i]=='Y') suf[i]=suf[i+1]+1;
else suf[i]=suf[i+1];
}
vector<int> ans(n+1);
for(int i=0;i<n+1;i++){
ans[i]=pre[i]+suf[i];
}
// now finding the minimum penalty index
int min=INT_MAX,idx=-1;
for(int i=0;i<n+1;i++){
if(ans[i]<min) {
min =ans[i];
idx=i;
}
}
return idx;

}
};

Q-3 Reducing Dishes (leetcode number-1402)

A chef has collected data on the satisfaction level of his n dishes. Chef can cook any
dish in 1 unit of time.

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

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

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

Example 1:

Input: satisfaction = [-1,-8,0,5,-9]


Output: 14
Explanation: After Removing the second and last dish, the maximum total like-time coefficient
will be equal to (-1*1 + 0*2 + 5*3 = 14).
Each dish is prepared in one unit of time.

Example 2:

Input: satisfaction = [4,3,2]


Output: 20
Explanation: Dishes can be prepared in any order, (2*1 + 3*2 + 4*3 = 20)
Example 3:

Input: satisfaction = [-1,-4,-5]


Output: 0
Explanation: People do not like the dishes. No dish is prepared.

Code

class Solution {
public:
int maxSatisfaction(vector<int>& satisfaction) {
int n=satisfaction.size();
// first sorting the array
sort(satisfaction.begin(),satisfaction.end());
// making suffix array with a twist
vector<int> suf(n);
for(int i=n-1;i>=0;i--){
if(i==n-1) suf[i]=satisfaction[i];
else suf[i]=satisfaction[i]+suf[i+1];
}
int idx=-1;
//findinf the pivot index
for(int i=0;i<n;i++){
if(suf[i]>=0){
idx=i;
break;
}
}
if(idx==-1) return 0;
int s=0,j=1;
for(int i=idx;i<n;i++){
s+=j*satisfaction[i];
j++;
}
return s;

}
};

Q-4 Longest subsequence with limited Sum (leetcode number- 2389)

You are given an integer array nums of length n, and an integer array queries of
length m.

Return an array answer of length m where answer[i] is the maximum size of


a subsequence that you can take from nums such that the sum of its elements is
less than or equal to queries[i].

A subsequence is an array that can be derived from another array by deleting


some or no elements without changing the order of the remaining elements.
Example 1:

Input: nums = [4,5,2,1], queries = [3,10,21]


Output: [2,3,4]
Explanation: We answer the queries as follows:
- The subsequence [2,1] has a sum less than or equal to 3. It can be proven that 2 is the
maximum size of such a subsequence, so answer[0] = 2.
- The subsequence [4,5,1] has a sum less than or equal to 10. It can be proven that 3 is the
maximum size of such a subsequence, so answer[1] = 3.
- The subsequence [4,5,2,1] has a sum less than or equal to 21. It can be proven that 4 is the
maximum size of such a subsequence, so answer[2] = 4.

Example 2:

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


Output: [0]
Explanation: The empty subsequence is the only subsequence that has a sum less than or
equal to 1, so answer[0] = 0.

Code

class Solution {
public:
vector<int> answerQueries(vector<int>& nums, vector<int>& queries) {
int n=nums.size();
int m=queries.size();
//first sorting the array
sort(nums.begin(),nums.end());
//prefix sum
for(int i=0;i<n;i++){
if(i==0) nums[i];
else nums[i]=nums[i]+nums[i-1];
}
// now making the required ans
// for(int i=0;i<m;i++){
// int c=0;
// for(int j=0;j<n;j++){
// if(nums[j]<=queries[i]) c=j+1;
// }
// queries[i]=c;
// }
// return queries; //t.C= O(nlogn)

//now making the required ans using binary search


for(int i=0;i<m;i++){
int lo=0;
int hi=n-1;
int ans=0;
while(lo<=hi){
int mid=lo+(hi-lo)/2;
// if(nums[mid]==queries[i]) ans= mid+1;
if(nums[mid]<=queries[i]) {
ans=mid+1;
lo=mid+1;
}
else hi=mid-1;
}
queries[i]=ans;
}
return queries; //t.c=(m+n(logn))
}
};

Q-5 Range Sum query- immutable (leetcode-303)

Given an integer array nums, handle multiple queries of the following type:

1. Calculate the sum of the elements of nums between


indices left and right inclusive where left <= right.

Implement the NumArray class:

 NumArray(int[] nums) Initializes the object with the integer array nums.
 int sumRange(int left, int right) Returns the sum of the elements of nums between
indices left and right inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right]).

Code

class NumArray {
public:
vector<int> pre;
NumArray(vector<int>& nums) {
pre=vector<int>(nums.size());
pre[0]=nums[0];
int n=nums.size();
for(int i=1;i<n;i++){
pre[i]=nums[i]+pre[i-1];
}

int sumRange(int left, int right) {


if(left==0) return pre[right];
return pre[right]-pre[left-1];
}
};

/**
* Your NumArray object will be instantiated and called as such:
* NumArray* obj = new NumArray(nums);
* int param_1 = obj->sumRange(left,right);
*/

Q-6 Find the score of all prefixes of an array (leetcode number- 2640)

We define the conversion array conver of an array arr as follows:

 conver[i] = arr[i] + max(arr[0..i]) where max(arr[0..i]) is the maximum value


of arr[j] over 0 <= j <= i.

We also define the score of an array arr as the sum of the values of the conversion
array of arr.

Given a 0-indexed integer array nums of length n, return an array ans of


length n where ans[i] is the score of the prefix nums[0..i].

Example 1:

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


Output: [4,10,24,36,56]
Explanation:
For the prefix [2], the conversion array is [4] hence the score is 4
For the prefix [2, 3], the conversion array is [4, 6] hence the score is 10
For the prefix [2, 3, 7], the conversion array is [4, 6, 14] hence the score is 24
For the prefix [2, 3, 7, 5], the conversion array is [4, 6, 14, 12] hence the score is 36
For the prefix [2, 3, 7, 5, 10], the conversion array is [4, 6, 14, 12, 20] hence the score is 56

Code

class Solution {
public:
vector<long long> findPrefixScore(vector<int>& nums) {
//making the conver array
int n=nums.size();
vector<long long> conver(n);
int max=INT_MIN;
for(int i=0;i<n;i++){
if(max<nums[i]) max=nums[i];
conver[i]=nums[i]+max;
}
// now making the ans array i.e. prefix of conver
for(int i=1;i<n;i++){
conver[i]=conver[i]+conver[i-1];
}
return conver;
}
};
Q-7 Corporate flight bookings (leetcode number-1109)

There are n flights that are labeled from 1 to n.


You are given an array of flight bookings bookings, where bookings[i] = [first , last ,
i i

seats ] represents a booking for flights first through last (inclusive) with seats seats
i i i i

reserved for each flight in the range.

Return an array answer of length n, where answer[i] is the total number of seats
reserved for flight i.

Example 1:

Input: bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5


Output: [10,55,45,25,25]
Explanation:
Flight labels: 1 2 3 4 5
Booking 1 reserved: 10 10
Booking 2 reserved: 20 20
Booking 3 reserved: 25 25 25 25
Total seats: 10 55 45 25 25
Hence, answer = [10,55,45,25,25]

Example 2:

Input: bookings = [[1,2,10],[2,2,15]], n = 2


Output: [10,25]
Explanation:
Flight labels: 1 2
Booking 1 reserved: 10 10
Booking 2 reserved: 15
Total seats: 10 25
Hence, answer = [10,25]

Code

class Solution {
public:
vector<int> corpFlightBookings(vector<vector<int>>& a, int n) {
vector<int> res(n,0);
for(int i=0;i<a.size();i++){
res[a[i][0]-1]+=a[i][2];
if(a[i][1]<n) res[a[i][1]]-=a[i][2];
}
for(int i=1;i<n;i++){
res[i]+=res[i-1];
}
return res;
}
};

Utility of sliding window


Q-1 Grumpy BookStore (leetcode number – 1052)
There is a bookstore owner that has a store open for n minutes. Every minute, some
number of customers enter the store. You are given an integer array customers of
length n where customers[i] is the number of the customer that enters the store at the
start of the i minute and all those customers leave after the end of that minute.
th

On some minutes, the bookstore owner is grumpy. You are given a binary array
grumpy where grumpy[i] is 1 if the bookstore owner is grumpy during the i minute,
th

and is 0 otherwise.

When the bookstore owner is grumpy, the customers of that minute are not satisfied,
otherwise, they are satisfied.

The bookstore owner knows a secret technique to keep themselves not grumpy
for minutes consecutive minutes, but can only use it once.

Return the maximum number of customers that can be satisfied throughout the day.

Example 1:

Input: customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], minutes = 3


Output: 16
Explanation: The bookstore owner keeps themselves not grumpy for the last 3 minutes.
The maximum number of customers that can be satisfied = 1 + 1 + 1 + 1 + 7 + 5 = 16.

Example 2:

Input: customers = [1], grumpy = [0], minutes = 1


Output: 1

Code

class Solution {
public:
int maxSatisfied(vector<int>& customers, vector<int>& grumpy, int
minutes) {
//[1,0,1,2,1,1,7,5]
//[0,1,0,1,0,1,0,1] 3min
//[0,1,0,1,0,0,0,0] ans=16
// finding the window of max loss of satisfaction
int n=customers.size();
int prevsum=0;
for(int k=0;k<minutes;k++){
if(grumpy[k]==1) prevsum+=customers[k];
}
int maxLoss=prevsum;
int idx=0;
int i=1;
int j=minutes;
while(j<n){
// int currentloss=prevsum;
// prevsum=prevsum-customers[i-1]*grumpy[i-
1]+customers[j]*grumpy[j];
int curr=prevsum;
if(grumpy[j]==1) curr+=customers[j];
if(grumpy[i-1]==1) curr+=(-customers[i-1]);
if(maxLoss<curr){
maxLoss=curr;
idx=i;
}
prevsum=curr;
// prevsum=currentloss;
i++;j++;
}
for(int l=idx;l<idx+minutes;l++){
grumpy[l]=0;
}
//sum of satisfaction
int ans=0;
for(int k=0;k<n;k++){
if(grumpy[k]==0) ans+=customers[k];
}
return ans;
}
};

Q-2 Miimum Size subarray sum (leetcode number -209)

Given an array of positive integers nums and a positive integer target,


return the minimal length of a

subarray
whose sum is greater than or equal to target. If there is no such subarray, return 0 instead.

Example 1:

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


Output: 2
Explanation: The subarray [4,3] has the minimal length under the problem constraint.

Example 2:

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


Output: 1

Example 3:

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


Output: 0
Code

class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int n=nums.size();
int i=0;
int j=0;
//edge case- checking if their id empty list
if(n==0) return 0;
int sum=nums[0];
//checking if the whole nums sum is less than target
int s=0;
for(int i=0;i<n;i++){
s+=nums[i];
}
if(s<target) return 0;
//vector of sizes
int smallest=INT_MAX;
while(j<n){
if(sum==target) {
if(smallest>j-i+1) smallest=j-i+1;
j++;
if(j<n){
sum+=nums[j];
}
}
else if(sum<target){
j++;
if (j<n) sum+=nums[j];
}
else if(sum>target){
if(smallest>j-i+1) smallest=j-i+1;
i++;
sum-=nums[i-1];
}
}

return smallest;
}
};

You might also like