Leetcode questions imp
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];
}
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--;
}
Example 1:
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.
Example 1:
Example 2:
Example 3:
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);
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);
}
};
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;
}
};
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.
|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;
}
};
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;
}
};
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:
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:
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:
Example 2:
Example 3:
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;
}
};
You are given an array time where time[i] denotes the time taken by the i bus to
th
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:
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;
}
};
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
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;
}
};
You are given an m x n integer matrix matrix with the following two properties:
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;
}
};
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;
}
};
Recursion
Q-1 Number of steps to reduce a number to zero {leet code-1342}
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:
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:
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;
}
};
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;
}
};
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:
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:
Example 2:
Example 3:
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;
}
};
Given an integer array nums, return the number of reverse pairs in the array.
Example 1:
Example 2:
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
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:
Example 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;
}
};
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:
Example 2:
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;
}
};
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
Example 2:
Example 3:
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;
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;
}
};
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:
Example 2:
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;
}
};
You are given an integer array nums of length n, and an integer array queries of
length m.
Example 2:
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)
Given an integer array nums, handle multiple queries of the following type:
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];
}
/**
* 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 also define the score of an array arr as the sum of the values of the conversion
array of arr.
Example 1:
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)
seats ] represents a booking for flights first through last (inclusive) with seats seats
i i i i
Return an array answer of length n, where answer[i] is the total number of seats
reserved for flight i.
Example 1:
Example 2:
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;
}
};
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:
Example 2:
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;
}
};
subarray
whose sum is greater than or equal to target. If there is no such subarray, return 0 instead.
Example 1:
Example 2:
Example 3:
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;
}
};