forked from manitgupt14/Amazon-Interview-Question
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrays.cpp
More file actions
1537 lines (1393 loc) · 43.3 KB
/
Arrays.cpp
File metadata and controls
1537 lines (1393 loc) · 43.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Arrays
1. Product of array Except itself
vector<long long int> productExceptSelf(vector<long long int>& arr, int n)
{
vector<long long> ans(n,0);
long long pro=1;
int count=0,ind=0;
for(int i=0; i<n; i++)
{
if(arr[i]!=0 && count<2)
pro = pro*arr[i];
else
{ count++; ind=i; }
}
if(count<1)
{
for(int i=0; i<n; i++)
ans[i]=pro/arr[i];
}
else if(count ==1)
ans[ind]=pro;
return ans;
}
2. Find Pivot Index-->sum strictly equal to left and right
// Prefix Sum Problem TC- O(n) SC -O(1)
int pivotIndex(vector<int>& nums)
{
int left=0, Tsum=0,n=nums.size();
for(int i=0; i<n; i++)
Tsum += nums[i];
for(int i=0; i<n; i++)
if(left== Tsum-left-nums[i])
return i;
else left +=nums[i];
return -1;
}
3. Move Zeroes At End
void moveZeroes(vector<int>& nums)
{
int i=0,j=0,n=nums.size();
while(i<n && j<n)
{
if(nums[i]==0)
{
j++;
if(j<n && nums[j]!=0)
{
swap(nums[i],nums[j]);
i++;
}
}
else {i++;j++;}
}
}
void moveZeroes(vector<int>& nums) {
for (int lastNonZeroFoundAt = 0, cur = 0; cur < nums.size(); cur++)
{
if (nums[cur] != 0) {
swap(nums[lastNonZeroFoundAt++], nums[cur]);
}
}
}
4. Rearrange an array with O(1) extra space ;
// arr[arr[i]] becomes == arr[i] ;
void arrange(long long arr[], int n)
{
for(int i=0;i<n ;i++)
arr[i] +=(arr[arr[i]%n])%n*n;
for(int i=0; i<n; i++)
arr[i] /=n;
}
4.(a) //Recursive approach space O(1)
void fun(long long arr[],int n,int k)
{
if(k>=n) return;
int i=arr[arr[k]];
fun(arr,n,k+1);
arr[k]=i;
}
void arrange(long long arr[], int n) {
fun(arr,n,0);
}
5. Majority Element in Array //{ count> n/2 }
// Moore's Majority Voting Algorithm
int majorityElement(int a[], int size)
{
int count =1,major = a[0];
for(int i= 1; i<size ; i++)
{
if(count==0)
{
major = a[i];
count=1;
}
else if(major==a[i]) //if current ele match
count++;
else count--;
}
count =0;
for(int i=0; i<size; i++)
if(a[i]==major) count++ ;
if(count>size/2) return major;
else return -1;
}
6. Cumulative frequency of elements in an unsorted array
vector<int> countFreq(int arr[], int n)
{
vector<int> ans;
map <int,int> ump; // declaring map
for(int i=0; i<n ;i++)
{
ump[arr[i]]++; //counting frequency key to value
}
int count=0;
for(auto it:ump)
{
count+=it.second; // getting mapped element with key
ans.push_back(count);
}
return ans;
}
7. Find duplicates in an array // Array returned //Modified
// 0<=arr[i]<=N-1
vector<int> duplicates(int arr[], int n)
{
vector<int> ans;
for(int i=0; i<n; i++)
{
arr[arr[i]%n] +=n;
}
for(int i=0; i<n;i++)
{
if((arr[i]/n)>1)
ans.push_back(i);
}
if(ans.size()==0)
ans.push_back(-1);
return ans;
}
8. Subarray with 0 sum // if Any Exists
bool subArrayExists(int arr[], int n)
{
int ans=0;
for(int i=1; i<n; i++)
{
arr[i] += arr[i-1] ; // prefix sum of Array
}
// if array repeats value then sum=0 occured
map<int,int> dup;
for(int i=0; i<n; i++)
{
dup[arr[i]]++; // maping element with frequency
if(dup[arr[i]]==2 or arr[i]==0)
{
ans=1; break;
}
}
return ans;
}
9. Common elements in 3 Sorted Array
// Take Care of Dublicates in Returned array
// Without any additional data stucture
vector <int> commonElements (int A[], int B[], int C[], int n1, int n2, int n3)
{
int i=0,j=0,k=0;
vector<int> v;
while(i<n1 && j<n2 && k<n3)
{
if(A[i]==B[j] && A[i]==C[k])
{
if(!v.empty() and v[v.size()-1]!=A[i])
v.push_back(A[i]);
else if(v.empty())
v.push_back(A[i]);
i++;j++;k++;
}
if(A[i]<B[j] || A[i]<C[k]) i++;
if(B[j]<A[i] || B[j]<C[k]) j++;
if(C[k]<A[i] || C[k]<B[j]) k++;
}
return v;
}
10. Circular Prime Number // 197, 719, 971
// if all circular rotation is prime
int isCircularPrime(int n)
{
int k =n,count =-1,digit;
while(k>0)
{
k/=10;
count++;
}
k=count;
if(isPrime(n))
{
while(k--) // rotations = count
{
digit = n%10;
n=n/10;
n= digit * pow(10,count)+n;
if(isPrime(n)) continue;
else return 0;
}
}
else return 0;
return 1;
}
11. bool isPrime (int n)
{
// Corner cases
if (n <= 1)
return false;
if (n <= 3)
return true;
// This is checked so that we can skip
// middle five numbers in below loop
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
12. Find Rank Transform in an Array
// Find Inedex of an Set in O(1)TC & O(N)SC
vector<int> arrayRankTransform(vector<int>& arr)
{
set <int> myset(arr.begin(),arr.end());
unordered_map<int ,int > hash;
int rank =1;
for(auto &i: myset) hash[i] = rank++;
for(auto &i: arr) i = hash[i];
return arr ;
}
13. Find Missing And Repeating // {1, 2, …N} size--> N
// Sign Changing Method to find Duplicate
int *findTwoElement(int *arr, int n)
{
int ans[2];
for(int i=0; i<n; i++)
{
int temp=abs(arr[i]);
if(arr[temp-1]<0)
{
ans[0]= temp;
continue;
}
if(arr[temp-1]>0)
arr[temp-1] *=-1;
}
for(int i=0; i<n; i++)
{
int temp=abs(arr[i]);
if(arr[i]>0)
{
ans[1]= i+1;
break;
}
}
return ans;
}
14. Array Subset of another array //O(n) ,O(n)
string isSubset(int a1[], int a2[], int n, int m)
{
unordered_set<int> s(a1, a1+n);
for(int i=0; i<m;i++)
{
if(s.count(a2[i]))
continue;
return "No";
}
return "Yes";
}
15. Count of Set Bits // complexity O(no. of set bits ~ logN)
int setBits(int N)
{
if(N==0)
return 0;
else
return 1+setBits(N & N-1);
}
16. Decimal to binary // Using Bitwise Operaters
// complexity O(logN)
void toBinary(int N)
{
int bin_Str[32],i;
for(i=0; N>0; i++)
{
bin_Str[i] = N&1;
N >>= 1 ; //equivalent to divide by 2
}
for(int j=i-1; j>=0; j--)
{
printf("%d",bin_Str[j]); //reverse Printing
}
}
15. Finding a Duplicate Number // All present except one
int findDuplicate(vector<int>& nums)
{
int ans=0 ; // N+1 elements
for(int i=0; i<nums.size(); i++)
ans= ans^nums[i];
// Taking XOR with 1 to N
for(int i=1; i<nums.size(); i++)
ans = ans^i;
return ans;
}
16. Power of 2 // N& N-1 counted set bits
bool isPowerofTwo(long long n)
{
if(n==0) return 0;
return !(n&n-1);
}
17. Sum equal to XOR in Given range
// (N & 1 ==0)counted unset bits
long sumXor(long n)
{
int ct=0;
while (n>0)
{
if((n&1)==0) ct++;
n>>=1;
}
return pow(2,ct);
}
18. Number of Flips to make binary A to B;
int numberOfFlips(int a, int b)
{
int count=0;
while( a>0 || b>0)
{
if(((a&1)^(b&1))==1) count++;
a>>=1; b>>=1;
}
return count;
}
19. Sort by Set Bit Count
class Solution{
public:
static int count(int n)
{
int res=0;
while(n>0)
{
res++;
n=n&(n-1);
}
return res;
}
static bool cmp(int a ,int b)
{
if(count(a)>count(b)) return true;
else return false;
}
void sortBySetBitCount(int arr[], int n)
{
stable_sort(arr,arr+n,cmp);
}
};
IMP-> if (X^Y) or (Y^Z) or (X^Z) == 1
// then at least one bit must be different
20. XOR Game gfg - Find n such that N&N+1==k ;
int xorCal(int k)
{
if(k==1) return 2;
int x = k & (k + 1);
if(x != 0) return -1;
else return (k+1)/2 -1;
}
21. Longest consecutive subsequence- numbers can be in any order.
// Input: N = 7 a[] = {2,6,1,9,4,5,3} % Output:6
int longestConsecutive(vector<int>& nums)
{
unordered_set<int> hash ;
for(auto i : nums)
hash.insert(i);
int max = 0 ;
for(auto i : hash)
{
int ct=0;
if(!hash.count(i-1))
{
while(hash.count(i++))
{
ct++;
if(max<ct) max = ct;
}
}
}
return max;
}
22. Count triplets with sum smaller than X - 3Sum
// Two Pointers Aapproach
long long countTriplets(long long arr[], int n, long long sum)
{
sort(arr,arr+n);
long long sol =0;
for(int i =0; i<n-2; i++)
{
int j=i+1,k=n-1;
while(j<k)
{
if(arr[i]+arr[j]+arr[k]<sum)
{
sol +=(k-j);
j++;
}
else k--;
}
}
return sol;
}
23. Maximum Subarray Sum // include negative numbers
long long maxSubarraySum(int arr[], int n)
{ // kadane's algo
long long maxm=0,max=arr[0];
for(int i=0; i<n ;i++)
{
if((arr[i]+maxm)>0)
{
maxm=maxm+arr[i];
if(max<maxm) max=maxm;
}
else maxm=0; //maxm = arr[0]
// for minimunm 1 element from arr
if(max<arr[i])
max = arr[i];
}
return max;
}
24. Rearrange Array Alternately - MAX MIN ALTERNATE
void rearrange(long long *arr, int n)
{
long long N = arr[n-1]+1;
long long i=0,j=n-1,k=0;
while(i<n)
{
arr[i] += (arr[j]%N)*N; // Storing max at even Index j
i++; // incremented traverse pointer
if(i<n)
{
arr[i] += (arr[k]%N)*N; // Storing min at odd index
}
i++; j--;k++; // incrementing all indices
}
for(int i=0; i<n ;i++)
{
arr[i] = (arr[i]/N); //we hashed Divident which is new ans
}
}
25. Count pairs with given SUM
int getPairsCount(int arr[], int n, int k)
{
unordered_map<int, int>m;
int count = 0;
for(int i = 0; i<n; i++)
{ // counting at the time before storing that element
// in this method we count only once (mutually)
count = count + m[k-arr[i]];
m[arr[i]]++; //storing in map
}
return count;
}
// optimised way only one loop required less calculations
int getPairsCount(int arr[], int n, int k)
{
unordered_map<int,int > hash;
int ans=0;
for(int i=0; i<n ;i++)
{
int temp = k-arr[i];
if(hash.count(temp))
ans += hash[temp]; // taking in account all present pairs
hash[arr[i]]++; // storing in map even if it is present
}
return ans ;
}
26. Middle Element in A,B,C in minimum Comparisons
int middle(int A, int B, int C)
{
int maxm = max(A,max(B,C));
int minm = min(A,min(B,C));
return (A+B+C-minm-maxm);
}
27. Maximum Absolute Sum of Any Subarray
// DP - Use of Kadanes Algo
// Crux of the prob. is magnitude is maxm when either it is
// maxm subarray sum or minimum subarray sum
int maxAbsoluteSum(vector<int>& arr)
{
int n = arr.size(),max=0,maxm=0,min=0,minm=0;
for(int i=0; i<n ;i++)
{
if(max+arr[i]>0)
{
max += arr[i];
if(maxm<max) maxm = max;
}
else max =0;
}
for(int i=0; i<n ; i++)
{
if(min+arr[i]<0)
{
min += arr[i];
if(min<minm)
minm =min;
}
else min = 0;
}
if(maxm>abs(minm)) return maxm;
else return abs(minm);
}
28. Segregate Even and Odd numbers using space
void segregateEvenOdd(int arr[], int n)
{
sort(arr,arr+n);
int a[n],j=0,k=0;
for(int i=0; i<n ; i++)
{
if(arr[i] &1);
else a[j++]=arr[i];
}
// after k==j odd will automatically present in a[]
for(int i=0; i<n; i++)
{
if(arr[i] &1)
a[j++]=arr[i];
arr[i]=a[k++];
}
}
28(b).Segregate Even and Odd numbers in O(1) --> constant space
void segregateEvenOdd(int arr[], int n)
{
int slow = -1;
for(int fast=0; fast<n; j++)
{
if(arr[j]%2==0)
{
slow++; // represents even indexes
swap(arr[slow],arr[fast]);
}
}
sort(arr,arr+slow+1);
sort(arr+slow+1,arr+n);
}
28(c) or Sort Array By Parity -- Leetcode
vector<int> sortArrayByParity(vector<int>& nums)
{
sort(nums.begin(),nums.end(),[](int a , int b){
if((a%2==0) and (b%2==1)) return true;
return false ;
});
return nums ;
}
29. Count Positive - Negative Pairs - Amazon Interview
long long countPositiveNegativePairs(int arr[], int n)
{
long long ans = 0;
unordered_map<int, int> m;
for(int i =0; i < n; i++) {
m[arr[i]]++;
}
for(auto it : m) {
int f = it.first;
if(m.find(-1 * f) != m.end())
{
if(m[-1 * f] > 0)
{
ans += (long long) m[f] * m[-1 * f];
m[f] = 0;
m[-1 * f] = 0;
}
}
}
return ans;
}
30. Three 3Sum Closest // If two close elemt ,return max one
// Input: target = 13 ,nums[] = {5,2,7,5} Output: 14
int threeSumClosest(vector<int> nums, int target)
{
sort(nums.begin(),nums.end());
int n = nums.size(),ans=0,min=INT_MAX; //for first condition
for(int i=0; i<n; i++)
{
int j= i+1,k=n-1;
while(j<k)
{
int sum = nums[i]+nums[j]+nums[k];
if(sum==target)
return target;
else if(sum>target)
{ // saving the max target
if(sum-target<=min)
{
ans = sum;
min = sum-target;
}
k--;
}
else
{
if(target-sum<min)
{
ans = sum;
min = target-sum;
}
j++;
}
}
}
return ans;
}
31. Three 3Sum - Find all Distinct Triplets sum equal to 0
// Input: nums = [-1,0,1,2,-1,-4]
// Output: [[-1,-1,2],[-1,0,1]]
vector<vector<int>> threeSum(vector<int>& nums)
{
sort(nums.begin(),nums.end());
int n = nums.size(),j,k=n-1;
vector<vector<int>> ans;
for(int i=0; i<n; i++)
{
if(i==0 or (i>0 and nums[i]!=nums[i-1]))
{
j= i+1; k=n-1;
while(j<k)
{
if(nums[i]+nums[j]+nums[k]==0)
{
vector<int> v = {nums[i],nums[j],nums[k]} ;
ans.push_back(v);
while(j<k && nums[j]==nums[j+1]) j++;
while(j<k && nums[k]==nums[k-1]) k--;
j++;k--;
}
else if(nums[i]+nums[j]+nums[k]>0) k--;
else j++;
}
}
}
return ans;
}
32. 4Sum Four Sum - Unique pairs sum equal to 0 (previoius)
vector<vector<int>> fourSum(vector<int>& arr, int target)
{
int n = arr.size();
sort(arr.begin(),arr.end()); // sorting to reduce complexity
vector<vector<int>> ans ;
for(int i=0; i<n-3; i++)
{
if(i>0 and arr[i]==arr[i-1]) continue; // must skip one pass
for(int j=i+1; j<n-2; j++)
{
if(j>i+1 and arr[j]==arr[j-1]) continue; // after one pass
int k=j+1, l=n-1;
while(k<l)
{
long long nums = 1LL*arr[i]+arr[j]+arr[k]+arr[l];
// calculation will held on long long before store
if(nums==target)
{
vector<int> temp = {arr[i],arr[j],arr[k],arr[l]} ;
ans.push_back(temp);
// Skipping Duplicates
while(k<l and arr[k]== arr[k+1]) k++; //check if next==prev
while(k<l and arr[l]== arr[l-1]) l--; // check if prev==next
k++; l--; // increment
}
else if(nums>target) l--;
else k++;
}
}
}
return ans ;
}
33. Longest/Largest subarray with 0 sum - O(N) -->TC & SC used Hashing
// idea is if sum 0 occur then prefix sum reapeats itself
int maxLen(vector<int>&A, int n)
{
int len, mxlen=0,presum=0;
unordered_map <int,int> hash;
// mapping 0 as -1 if 0 occur instead of reapeation
hash[presum] = -1; // It Adds Length of +1 when 0 occurs when presum 0 occurs
// it means all element till that point giving sum==0;
for(int i=0; i<n; i++)
{
presum += A[i]; // computing Prefix sum
if(hash.count(presum))
{
len = i - hash[presum] ;
mxlen = max(mxlen,len);
}
else hash[presum] = i; // mapping a index of presum
}
return mxlen ;
}
34. Next Permutation or Next Greater Permutation
void nextPermutation(vector<int>& nums)
{
int n = nums.size(); //size of array
// First of All We have to Find a Right Most Peak
int peakInd = -1; // Assuming Initially No Peak Index
int i=1; // traverse Pointer
while(i<n)
{
if(nums[i]>nums[i-1])
peakInd = i;
i++;
}
// If No Peak found sequence is in Descensing Order
// reversing the Sequence
if(peakInd==-1)
{
for(int i=0,j=n-1; i<j; i++,j--)
swap(nums[i],nums[j]);
return ;
}
// Special Case if peak is Available but there is an element
// which is greater than prepeak which also perform as a peak for that
// for Next perMutation we must use minimum weight
int prev = peakInd-1,min=peakInd;
for(int i=peakInd+1; i<n ;i++)
{
if(nums[prev]<nums[i] and nums[peakInd]>nums[i])
min = i; // selecting the right most index for min weight
}
swap(nums[min],nums[prev]);
sort(nums.begin()+peakInd,nums.end()); // sorting for ASC order
}
35. Next Greater Element III - Next Greater Integer (if pOssible)
// Return -1 if it not fit in 32 bit Integer // 0ms Soln
int nextGreaterElement(int n)
{
string nums = to_string(n);
string max = to_string (INT_MAX);
int pkInd =-1,size = nums.size();
for(int i=1; i<size ;i++)
{
if(nums[i]>nums[i-1])
pkInd = i;
}
if(pkInd ==-1) return -1;
int prev = pkInd-1,min=pkInd;
for(int i=pkInd+1; i<size; i++)
{
if(nums[i]>nums[prev] and nums[i]<nums[pkInd])
min = i;
}
swap(nums[min],nums[prev]);
sort(nums.begin()+pkInd,nums.end());
if(nums.size()<10 or nums<=max)
{
n = stoi(nums);
return n;
}
else return -1;
}
36. Merge Sorted Array in Given Space - O(n)
// Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
// Output: [1,2,2,3,5,6]
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n)
{
int i=m-1, j=n-1, k=m+n-1;
// pointers from back Direction
while(i>=0 && j>=0)
{
if(nums1[i]>nums2[j])
{
// Copying greater element in Last
nums1[k] = nums1[i];
k--; i--;
}
else
{
nums1[k] = nums2[j];
k--; j--;
}
}
while(j>=0)
{
// copy remaining element of nums2 in nums1
nums1[k] = nums2[j];
k--; j--;
}
// No need to copy nums1 they are already in sorted Order
}
37. Rotate an Array in Place - Left Rotation
void rotateArr(int arr[], int d, int n)
{
// for left Rotation rotate(d,n-d,n);
// for right rotation R(n-d,d,n);
d %= n ;
int s=0,e=d-1;
while(s<e)
swap(arr[s++],arr[e--]);
s=d; e=n-1;
while(s<e)
swap(arr[s++],arr[e--]);
s=0; e= n-1;
while(s<e)
swap(arr[s++],arr[e--]);
}
38. Merge Intervals- Overlapping Intervals
39. Continuous Subarray Sum - Divisible by k (size>=2) - 523 LeetCode
40. Arithmetic Slices - Contiguous A.P. Subarray total count
int numberOfArithmeticSlices(vector<int>& nums)
{
int k=0,ans=0,n=nums.size();
for(int i=1; i<n-1; i++)
{
if(nums[i]-nums[i-1]==nums[i+1]-nums[i])
{
ans += k+1;
k++; // subarray increased by one contiguous array
}
else k=0;
}
return ans ;
}
41. Count Numbers with Unique Digits
// Input: n = 2 Output: 91
// excluding 11,22,33,44,55,66,77,88,99
int countNumbersWithUniqueDigits(int n)
{
if(n==0) return 1 ;
int UniqueDigits=9,num_avail = 9,res=10;
while(n-->1 and num_avail>0)
{
UniqueDigits *= num_avail--;
res += UniqueDigits;
}
return res;
}
42. Maximum Product Subarray
// Kadene's and Reverse Kadane's
// take both Positive and Negative as both can increase the ans
// 0 always decrese the ans so leave it
long long maxProduct(vector<int> nums, int n)
{
long long maxpro=INT_MIN,pro=1;
for(int i=0 ; i<n ;i++)
{
pro *= nums[i];
maxpro = max(maxpro,pro);
if(nums[i]==0) pro =1 ;
}
long long maxpro1=INT_MIN;pro=1;
for(int i=n-1 ; i>=0 ;i--)
{
pro *= nums[i];
maxpro1 = max(maxpro1,pro);
if(nums[i]==0) pro =1;
}
return max(maxpro1,maxpro);
}
43. Reverse Bits in an 32 bit Unsinged integer
uint32_t reverseBits(uint32_t X)
{
long long ans=0,t=31; // 31 cycle
while(t--)
{
if(X&1) ans |= 1; // if last bit is 1 make ans first bit 1
X>>=1; ans<<=1;
}
if(X&1) ans |= 1; // checking last bit
return ans;
}
44.Counting Bits in every no. in [0,n] // TC->O(n) SC->O(1)
vector<int> countBits(int n)
{
vector<int> ans(n+1); // pre declarartion for 0 to n
for(int i=0 ; i<=n ; i++)
{
if(i<2) ans[i] = i; // saving bits 0 ,1 for record
else
{
if(i&1) // checking even odd
ans[i] = (ans[i>>1]+1) ;
// if odd then it must have more bit than it's
// right shifted element i/2
// right shift already present in array
else
ans[i] = ans[i>>1] ;
// dont pushback if size is pre declared
}
}
return ans ;
}
45. int twoCitySchedCost(vector<vector<int>>& costs)
{
// Leetcode Daily Challenge Optimized Solution
// Use of lambda Function it is faster than Comparater
// Greedy Approach // sorting according to Difference
sort(costs.begin(), costs.end(), [](vector<int>& a, vector<int>& b){
return (a[0] - a[1]) < (b[0] - b[1]);
});
int n = costs.size() / 2;
int res = 0;
for (int i = 0; i < n; i++){
res += costs[i][0] + costs[i + n][1];
}
return res;
}
46. Pair Sum -Code Ninja (2Sum) All pair
vector<vector<int>> pairSum(vector<int> &arr, int s)
{
sort(arr.begin(),arr.end());
vector<vector<int>> ans;
unordered_map <int,int> hash;