-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharray_medium_leetcode.go
More file actions
2126 lines (1914 loc) · 53.8 KB
/
array_medium_leetcode.go
File metadata and controls
2126 lines (1914 loc) · 53.8 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
package main
import (
"container/heap"
"fmt"
"math"
"sort"
"strings"
)
func main() {
// triangle := [][]int{
// {2},
// {3, 4},
// {6, 5, 7},
// {4, 1, 8, 3},
// }
// fmt.Println(minimumTotal(triangle))
//strs := []string{"10", "0001", "111001", "1", "0"}
// nums := [][]int{
// {-1},
// {2},
// {3},
// }
// nums := []int{1, 2, 4, 8, 9, -2, -7, 3}
// fmt.Println(letterCombinations("234"))
// strs := []string{"eat", "tea", "tan", "ate", "nat", "bat"}
// // fmt.Println(groupAnagrams(strs))
// fmt.Println(groupAnagramsUsingHashMap(strs))
// fmt.Println(checkTwoStringAnnagram("eat", "tea"))
// fmt.Println(sumSubarrayMins([]int{3, 1, 2, 4}))
// s := "aaaaab"
// wordDict := []string{"a", "aa", "aaa", "aaaa", "aaaaa"}
// fmt.Println(wordBreak(s, wordDict))
fmt.Println(partitionPalindrome("cbbbcc"))
}
/**
* Problem : 120. Triangle
* Given a triangle array, return the minimum path sum from top to bottom.
* Solution: Use bottom up approach and update the value of upper array while adding the min of below array¯
**/
func minimumTotal(triangle [][]int) int {
for i := len(triangle) - 2; i >= 0; i-- {
for j := 0; j < len(triangle[i]); j++ {
triangle[i][j] += findMin(triangle[i+1][j], triangle[i+1][j+1])
}
fmt.Println(triangle)
}
return triangle[0][0]
}
func findMin(v1, v2 int) int {
if v1 > v2 {
return v2
}
return v1
}
/**
* Problem : 15. 3Sum
* Problem: Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
* Notice that the solution set must not contain duplicate triplets.
* Input: nums = [-1,0,1,2,-1,-4]
* Output: [[-1,-1,2],[-1,0,1]]
*/
func threeSumBruteForceSolution(nums []int) [][]int {
fmt.Println("Given Array: ", nums)
//foundZeroSum := false
mapStoreTwosum := make([][]int, int(len(nums)/3))
// fmt.Println(mapStoreTwosum)
for i := 0; i < len(nums); i++ {
for j := i + 1; j < len(nums); j++ {
for k := j + 1; k < len(nums); k++ {
if nums[i]+nums[j]+nums[k] == 0 && i != j && i != k && j != k {
//foundZeroSum = true
fmt.Printf("i=%d, j=%d, k=%d \n", i, j, k)
mapStoreTwosum[i] = []int{nums[k], nums[i], nums[j]}
}
}
}
}
fmt.Println(mapStoreTwosum)
return mapStoreTwosum
}
/**
* Problem : 15. 3Sum
* Problem: Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
* Notice that the solution set must not contain duplicate triplets.
* Input: nums = [-1,0,1,2,-1,-4]
* Output: [[-1,-1,2],[-1,0,1]]
*/
func threeSumOptimalSolution(nums []int) [][]int {
fmt.Println("Given Array: ", nums)
sort.Ints(nums)
fmt.Println("Sorted Array: ", nums)
//foundZeroSum := false
mapStoreTwosum := [][]int{}
low := 0
right := len(nums) - 1
sum := 0
// fmt.Println(mapStoreTwosum)
for i := 0; i < len(nums)-2; i++ {
sum = -nums[i]
low = i + 1
fmt.Println(i, nums[low], nums[right], sum)
for low < right {
//fmt.Println(i, low, right, nums[low]+nums[right], sum)
if nums[low]+nums[right] == sum {
//mapStoreTwosum[i] = []int{nums[i], nums[low], nums[right]}
mapStoreTwosum = append(mapStoreTwosum, []int{nums[i], nums[low], nums[right]})
//fmt.Println(nums[i], nums[low], nums[right])
low++
right--
} else {
right--
}
if nums[low]+nums[right] < sum {
low++
}
//fmt.Println(nums[i], nums[low], nums[right])
}
}
fmt.Println(mapStoreTwosum, sum)
return mapStoreTwosum
}
/**
* Problem: 189. Rotate Array
* Given an integer array nums, rotate the array to the right by k steps, where k is non-negative.
* Input: nums = [1,2,3,4,5,6,7], k = 3
* Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
*/
func BruteForceRotate(nums []int, k int) {
fmt.Println("Given Array:", nums)
// for i := len(nums); i > len(nums)-k; i-- {
// fmt.Println(i)
// //nums = append(nums[i:], nums[:i]...)
// nums[i+1] = nums[i]
// }
/** Brute force 1
for i := 0; i < k; i++ {
var j, last int
length := len(nums)
last = nums[length-1]
for j = length - 1; j > 0; j-- {
nums[j] = nums[j-1]
}
nums[0] = last
}
*/
arrLen := len(nums)
k = k % arrLen
tmp := make([]int, k)
m := 0
for i := (arrLen - k); i < len(nums); i++ {
tmp[m] = nums[i]
m++
}
// tmpElem := nums[k%arrLen]
for j := (arrLen - 1); j >= k; j-- {
nums[j] = nums[j-k]
}
//nums[arrLen-1] = tmpElem
for l := 0; l < k; l++ {
nums[l] = tmp[l]
}
fmt.Println(nums, tmp)
}
/**
* Problem: 189. Rotate Array
* Given an integer array nums, rotate the array to the right by k steps, where k is non-negative.
* Input: nums = [1,2,3,4,5,6,7], k = 3
* Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
*/
func OptimalRotate(nums []int, k int) {
k = k % len(nums) // get the modulo of k because if the array lenth 4 and we want rotate this 10 times that means 4+4+2.
// Basically we rotate array for 4 times its return to the same as original array. And we do this another 4 time then returns the same.
// So this 4+4+2 means will have to rotate the array only 2
reverse(nums, 0, len(nums)-1-k)
reverse(nums, len(nums)-k, len(nums)-1)
reverse(nums, 0, len(nums)-1)
}
func reverse(nums []int, startIndex int, endIndex int) {
if startIndex == endIndex {
return
}
for startIndex < endIndex {
nums[startIndex], nums[endIndex] = nums[endIndex], nums[startIndex]
startIndex++
endIndex--
}
}
/**
Problem : 523. Continuous Subarray Sum
Given an integer array nums and an integer k, return true if nums has a good subarray or false otherwise.
A good subarray is a subarray where:
its length is at least two, and
the sum of the elements of the subarray is a multiple of k.
Note that:
A subarray is a contiguous part of the array.
An integer x is a multiple of k if there exists an integer n such that x = n * k. 0 is always a multiple of k
**/
func checkSubarraySum(nums []int, k int) bool {
tmpMod := 0
totalSum := 0
for i := 0; i < len(nums); i++ {
totalSum += nums[i]
if i < 1 {
continue
}
tmpMod = nums[i] % k
if (tmpMod+nums[i])%k == 0 {
return true
}
}
return (totalSum % k) == 0
}
/**
* 167. Two Sum II - Input Array Is Sorted
* Input: numbers = [2,7,11,15], target = 9
* Output: [1,2]
* Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2].
*/
func twoSum(numbers []int, target int) []int {
fmt.Println("Given Array: ", numbers)
var i, j = 0, len(numbers) - 1
for i < len(numbers) && j >= 0 {
fmt.Println(numbers[i], numbers[j], i, j)
if numbers[i]+numbers[j] == target {
return []int{i + 1, j + 1}
}
if i >= j {
break
}
if numbers[i]+numbers[j] < target {
i++
} else {
j--
}
}
return []int{}
}
/**
* Problem: 53. Maximum Subarray
* Given an integer array nums, find the subarray with the largest sum, and return its sum.
* 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.
* Solution: Kadanes alogorithm to calculate the max sum. The intuition of the algorithm is not to consider the subarray as a part of the answer if its sum is less than 0
*/
func maxSubArray(nums []int) int {
largestSum := math.MinInt32
sum := 0
for i := 0; i < len(nums); i++ {
sum += nums[i]
if sum > largestSum {
largestSum = sum
}
if sum < 0 {
sum = 0
}
}
return largestSum
}
/**
* Problem: Print the subarray with maximum sum
* Given an integer array nums, find the subarray with the largest sum, and return its sum.
* Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
* Output:
* The subarray is: [4 -1 2 1 ]
* The maximum subarray sum is: 6
*/
func PrintMaxSubarrayofSum(nums []int) []int {
var maxSum, sum, start, startPos, endPos = math.MinInt16, 0, 0, 0, 0
for i := 0; i < len(nums); i++ {
if sum == 0 {
start = i
}
sum += nums[i]
if sum > maxSum {
startPos = start
endPos = i
maxSum = sum
}
if sum < 0 {
sum = 0
}
}
fmt.Println(start, startPos, endPos)
return nums[startPos : endPos+1]
}
/*
*
* Problem: 2149. Rearrange Array Elements by Sign
* You are given a 0-indexed integer array nums of even length consisting of an equal number of positive and negative integers.
* You should rearrange the elements of nums such that the modified array follows the given conditions:
* Every consecutive pair of integers have opposite signs.
* For all integers with the same sign, the order in which they were present in nums is preserved.
* The rearranged array begins with a positive integer.
* Return the modified array after rearranging the elements to satisfy the aforementioned conditions.
* Input: nums = [3,1,-2,-5,2,-4]
Output: [3,-2,1,-5,2,-4]
Explanation:
The positive integers in nums are [3,1,2]. The negative integers are [-2,-5,-4].
The only possible way to rearrange them such that they satisfy all conditions is [3,-2,1,-5,2,-4].
Other ways such as [1,-2,2,-5,3,-4], [3,1,2,-2,-5,-4], [-2,3,-5,1,-4,2] are incorrect because they do not satisfy one or more conditions.
*/
func rearrangeArrayBruteForceSolution(nums []int) []int {
var posArray, negArray = []int{}, []int{}
for i := 0; i < len(nums); i++ {
if nums[i] > 0 {
posArray = append(posArray, nums[i])
} else {
negArray = append(negArray, nums[i])
}
}
for i := 0; i < int(len(nums)/2); i++ {
nums[i*2] = posArray[i]
nums[i*2+1] = negArray[i]
}
return nums
}
/**
* Input: nums = [3,1,-2,-5,2,-4]
Output: [3,-2,1,-5,2,-4]
Explanation:
The positive integers in nums are [3,1,2]. The negative integers are [-2,-5,-4].
The only possible way to rearrange them such that they satisfy all conditions is [3,-2,1,-5,2,-4].
Other ways such as [1,-2,2,-5,3,-4], [3,1,2,-2,-5,-4], [-2,3,-5,1,-4,2] are incorrect because they do not satisfy one or more conditions.
*/
func rearrangeArrayBetter(nums []int) []int {
var ansArray, posIndex, negIndex = make([]int, len(nums)), 0, 0
for i := 0; i < len(nums); i++ {
if nums[i] < 0 {
ansArray[negIndex*2+1] = nums[i]
negIndex++
} else {
ansArray[posIndex*2] = nums[i]
posIndex++
}
}
fmt.Println(ansArray)
return ansArray
}
/**
* Problem: 31. Next Permutation
* Input: nums = [1,2,3]
* Output: [1,3,2]
*/
func nextPermutation(nums []int) {
fmt.Println("Input Array", nums)
var index, arrLen, j, k = -1, len(nums), 0, len(nums) - 1
for i := arrLen - 2; i >= 0; i-- {
if nums[i] < nums[i+1] {
index = i
break
}
}
if index == -1 {
for j < k {
nums[j], nums[k] = nums[k], nums[j]
j++
k--
}
} else {
for i := arrLen - 1; i >= 0; i-- {
if nums[i] > nums[index] {
nums[i], nums[index] = nums[index], nums[i]
break
}
}
j = index + 1
for j < k {
nums[j], nums[k] = nums[k], nums[j]
j++
k--
}
}
}
/**
* Leaders in array problem
* Given an array, print all the elements which are leaders. A Leader is an element that is greater than all of the elements on its right side in the array.
* Input : arr = [4, 7, 1, 0]
* Output: arr = [7, 1, 0]
* Solution: Two pointer approach
*/
func leaderInArray(nums []int) []int {
fmt.Println("Given array: ", nums)
leaderArray := []int{}
//leaderArray = append(leaderArray, nums[len(nums)-1])
var i, j = 0, len(nums) - 1
for i < j {
isLeader := false
if nums[i] > nums[j] {
j--
isLeader = true
} else {
i++
j = len(nums) - 1
isLeader = false
}
if i == j {
if isLeader {
leaderArray = append(leaderArray, nums[i])
}
i++
j = len(nums) - 1
}
}
leaderArray = append(leaderArray, nums[j])
return leaderArray
}
func leaderInArrayBetter(nums []int) []int {
fmt.Println("Given array: ", nums)
leaderArray := []int{}
max := nums[len(nums)-1]
for i := len(nums) - 2; i >= 0; i-- {
if nums[i] > max {
leaderArray = append(leaderArray, nums[i])
max = nums[i]
}
}
leaderArray = append(leaderArray, nums[len(nums)-1])
return leaderArray
}
/*
* Problem: 128. Longest Consecutive Sequence
* Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
* You must write an algorithm that runs in O(n) time.
* Input: nums = [100,4,200,1,3,2]
* Output: 4
* Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
*/
func longestConsecutiveBruteForce(nums []int) int {
longestStreak := 1
if len(nums) == 0 {
return len(nums)
}
for i := 0; i < len(nums); i++ {
currentNumber := nums[i]
count := 1
for findInArray(currentNumber+1, nums) {
currentNumber += 1
count += 1
}
if count > longestStreak {
longestStreak = count
}
}
return longestStreak
}
func findInArray(elem int, nums []int) bool {
for j := 0; j < len(nums); j++ {
if nums[j] == elem {
return true
}
}
return false
}
func longestConsecutiveBetter(nums []int) int {
//fmt.Println("Given array: ", nums)
var longestStreak, tmpStreak = 1, 1
if len(nums) == 0 || len(nums) == 1 {
return len(nums)
}
sort.Ints(nums)
for k := 1; k < len(nums); k++ {
if nums[k] == nums[k-1]+1 {
tmpStreak++
} else if nums[k] != nums[k-1] {
tmpStreak = 1
}
if tmpStreak > longestStreak {
longestStreak = tmpStreak
}
}
fmt.Println(nums, longestStreak)
return longestStreak
}
/*
* Solution: Have unordered set or map to store all the elem of the given array and try to to least number from the map.
* If this exist then start the iteration number + 1 if there increase the count and longeststreak as well.
*/
func longestConsecutiveOptimalSolution(nums []int) int {
fmt.Println("Given array: ", nums)
longestStreak := 1
if len(nums) == 0 {
return 0
}
numMap := make(map[int]struct{})
for _, v := range nums {
numMap[v] = struct{}{}
}
for k := range numMap {
if _, ok := numMap[k-1]; !ok {
leastNumber := k
count := 1
_, findNext := numMap[leastNumber+1]
for findNext {
leastNumber += 1
count += 1
_, findNext = numMap[leastNumber+1]
}
if count > longestStreak {
longestStreak = count
}
}
}
//fmt.Println(numMap)
return longestStreak
}
/*
* Problem : 73. Set Matrix Zeroes
* Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's.
* Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
* Output: [[1,0,1],[0,0,0],[1,0,1]]
* Solution Time Compexity: O(n^3), space complexity: 0(1)
*/
func setZeroesBruteForceSolution(matrix [][]int) {
m := len(matrix)
n := len(matrix[0])
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if matrix[i][j] == 0 {
markRow(i, n, matrix)
markCol(j, m, matrix)
}
}
}
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if matrix[i][j] == math.MinInt64 {
matrix[i][j] = 0
}
}
}
}
func markRow(row int, n int, matrix [][]int) {
for i := 0; i < n; i++ {
if matrix[row][i] != 0 {
matrix[row][i] = math.MinInt64
}
}
}
func markCol(col int, m int, matrix [][]int) {
for i := 0; i < m; i++ {
fmt.Println(i, col)
if matrix[i][col] != 0 {
matrix[i][col] = math.MinInt64
}
}
}
// Solution: Time complexity: O(n^2), Space Complexity: O(m) + O(n)
func setZeroesBetterSolution(matrix [][]int) {
m := len(matrix)
n := len(matrix[0])
row := make([]int, m) // Take row array of m length
col := make([]int, n) // Take col array of n length
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if matrix[i][j] == 0 {
row[i] = 1
col[j] = 1
}
}
}
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if row[i] == 1 || col[j] == 1 {
matrix[i][j] = 0
}
}
}
}
func setZeroesOptimalSolution(matrix [][]int) {
m := len(matrix)
n := len(matrix[0])
col0 := 1
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if matrix[i][j] == 0 {
matrix[i][0] = 0 // mark row as 0
if j != 0 {
matrix[0][j] = 0 // mark col as 0
} else {
col0 = 0
}
}
}
}
for i := 1; i < m; i++ {
for j := 1; j < n; j++ {
if matrix[i][j] != 0 {
//check for row and column
if matrix[0][j] == 0 || matrix[i][0] == 0 {
matrix[i][j] = 0
}
}
}
}
if matrix[0][0] == 0 {
for j := 0; j < n; j++ {
matrix[0][j] = 0
}
}
if col0 == 0 {
for i := 0; i < m; i++ {
matrix[i][0] = 0
}
}
}
/**
* Problem: 48. Rotate Image
* You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise)
* You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
* Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
* Output: [[7,4,1],[8,5,2],[9,6,3]]
**/
func rotateBruteForceSolution(matrix [][]int) {
var m, n = len(matrix), len(matrix[0])
dummyMatrix := make([][]int, m)
for i := 0; i < m; i++ {
dummyMatrix[i] = make([]int, n)
}
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
dummyMatrix[j][n-1-i] = matrix[i][j]
// matrix[j][n-1-i] = matrix[i][j]
// if j == n-1 || (i == m-1 && j > 0) {
// matrix[j][n-1-i] = dummyMatrix[i][j]
// }
// if i > 0 && j > i {
// matrix[j][n-1-i] = dummyMatrix[i][j]
// }
// if j >= n-1-i {
// fmt.Println(j, dummyMatrix[i][j], matrix[i][j])
// }
// if n-1-i == j && j >= i {
// matrix[j][n-1-i] = dummyMatrix[i][j]
// }
}
}
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
fmt.Print(" ", dummyMatrix[i][j])
}
fmt.Print("\n")
}
fmt.Print("\n")
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
fmt.Print(" ", matrix[i][j])
}
fmt.Print("\n")
}
fmt.Println(matrix)
}
/**
* Solution:
* 1. Transpose the matrix first which means col becomes row and row becomes col
* 2. Reverse the earch row and you will be achieve the answer.
*/
func rotateOptimalSolution(matrix [][]int) {
var m, n = len(matrix), len(matrix[0])
for i := 0; i < m-1; i++ {
for j := i + 1; j < n; j++ {
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] // Transpose the matrix logic
}
}
for i := 0; i < m; i++ {
for j := 0; j < n/2; j++ {
matrix[i][j], matrix[i][n-1-j] = matrix[i][n-1-j], matrix[i][j] // reverse the matrix
}
}
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
fmt.Print(" ", matrix[i][j])
}
fmt.Print("\n")
}
}
/**
* Problem: 54. Spiral Matrix
* Given an m x n matrix, return all elements of the matrix in spiral order.
* Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
* Output: [1,2,3,6,9,8,7,4,5]
* Solution: right->bottom->left->top approach to traverse the matrix
*/
func spiralOrder(matrix [][]int) []int {
for i := 0; i < len(matrix); i++ {
for j := 0; j < len(matrix[0]); j++ {
fmt.Print(" ", matrix[i][j])
}
fmt.Print("\n")
}
var top, bottom, left, right, matrixVal = 0, len(matrix) - 1, 0, len(matrix[0]) - 1, []int{}
for left <= right && top <= bottom {
for i := left; i <= right; i++ {
matrixVal = append(matrixVal, matrix[top][i])
}
top++
for i := top; i <= bottom; i++ {
matrixVal = append(matrixVal, matrix[i][right])
}
right--
if top <= bottom {
for i := right; i >= left; i-- {
matrixVal = append(matrixVal, matrix[bottom][i])
}
bottom--
}
if left <= right {
for i := bottom; i >= top; i-- {
matrixVal = append(matrixVal, matrix[i][left])
}
left++
}
}
return matrixVal
}
/**
* Problem: 560. Subarray Sum Equals K
* Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k.
* A subarray is a contiguous non-empty sequence of elements within an array.
* Input: nums = [1,1,1], k = 2
* Output: 2
*/
func subarraySumBruteForce(nums []int, k int) int {
var count int
//var totalSum int
for i := 0; i < len(nums); i++ {
var sum = nums[i]
if sum == k {
count += 1
}
for j := i + 1; j < len(nums); j++ {
sum += nums[j]
if sum == k {
count += 1
if (i == 0 && j == len(nums)-1) && sum-nums[i] <= k {
i = j
break
}
}
}
}
return count
}
/**
* Optimal solution using two pointer equidorectional approach
*/
func subarraySumOptimal(nums []int, k int) int {
var count, prefixSum = 0, 0
unorderedmMap := make(map[int]int, len(nums))
unorderedmMap[0] = 1
for i := 0; i < len(nums); i++ {
prefixSum += nums[i]
remove := prefixSum - k
count += unorderedmMap[remove]
unorderedmMap[prefixSum] += 1
}
return count
}
/**
* Problem: 215. Kth Largest Element in an Array
* Given an integer array nums and an integer k, return the kth largest element in the array.
* Note that it is the kth largest element in the sorted order, not the kth distinct element.
* Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
* Output: 4
* This solution work only incase of positive integers
*/
func findKthLargestOptimal(nums []int, k int) int {
fmt.Println("Given Array: ", nums)
maxElement := nums[0]
var count int
for i := 0; i < len(nums); i++ {
if maxElement < nums[i] {
maxElement = nums[i]
}
}
fmt.Println(maxElement)
freqArray := make([]int, maxElement+1)
for i := 0; i < len(nums); i++ {
freqArray[nums[i]]++
}
for i := maxElement; i > 0; i-- {
if freqArray[i] != 0 {
count += freqArray[i]
if int(count) >= k {
return i
}
}
}
return 0
}
func findKthLargest(nums []int, k int) int {
fmt.Println("Given Array: ", nums)
if k < 1 || k > len(nums) {
return -1 // Invalid k value
}
return quickSelect(nums, 0, len(nums)-1, len(nums)-k)
}
func quickSelect(nums []int, start, end, k int) int {
if start == end {
return nums[start]
}
pivotIndex := partition(nums, start, end)
if pivotIndex == k {
return nums[pivotIndex]
} else if k < pivotIndex {
return quickSelect(nums, start, pivotIndex-1, k)
} else {
return quickSelect(nums, pivotIndex+1, end, k)
}
}
func partition(nums []int, start, end int) int {
pivot := nums[end]
i := start - 1
for j := start; j < end; j++ {
if nums[j] <= pivot {
i++
nums[i], nums[j] = nums[j], nums[i]
}
}
nums[i+1], nums[end] = nums[end], nums[i+1]
fmt.Println(nums)
return i + 1
}
func findPivotIndex(nums []int, start, end int) int {
pivot := nums[end] // find the pivot and place its correct order
j := start - 1
for i := start; i < end; i++ {
if nums[i] <= pivot {
j++
nums[i], nums[j] = nums[j], nums[i]
}
}
nums[j+1], nums[end] = nums[end], nums[j+1]
//fmt.Println(nums)
return j + 1
}
/**
* NAother solution is to check the constraint for elements val and create a slice with 2*num[i] contraint value.
* Next, store all the numbers there with constaraint addition nums[i] + 10^4 in this question.
* Next, check the frequency for each element and sum it up, untill you get sum >= k
*/
func findKthLargestAnotherOptimalSolution(nums []int, k int) int {
count := make([]int, 20001)
for _, num := range nums {
count[num+10000]++
}
running := 0
for i := len(count) - 1; i >= 0; i-- {
if count[i] > 0 {
running += count[i]
if running >= k {
return i - 10000
}
}
}
return -1
}
/**
* Problem: 347. Top K Frequent Elements
* Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
* Input: nums = [1,1,1,2,2,3], k = 2
* Output: [1,2]
* Intuition: counting sort algorithm
*/
func topKFrequent(nums []int, k int) []int {
fmt.Println("Given Array: ", nums)
ans := []int{}
countArray := make(map[int]int)
for i := 0; i < len(nums); i++ {
countArray[nums[i]]++
}
countFreq := make(map[int][]int, len(countArray))
for key, freq := range countArray {
countFreq[freq] = append(countFreq[freq], key)
}
for i := len(countArray) + 1; len(ans) <= k; i-- {
ans = append(ans, countFreq[i]...)
if len(ans) >= k {
return ans[0:k]
}
}
return ans
}
func findKthLargestHeap(nums []int, k int) int {
h := IntHeap(nums)
heap.Init(&h)
for i := 0; i < len(nums)-k; i++ {
heap.Pop(&h)
}
return heap.Pop(&h).(int)
}
type IntHeap []int
type any = interface{}
func (h IntHeap) Len() int { return len(h) }