-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path12-top-k-elements.rb
716 lines (612 loc) · 15.8 KB
/
12-top-k-elements.rb
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
puts "Top k numbers"
class Heap
attr_accessor :arr, :comparator
def initialize(&comparator)
self.comparator = comparator
self.arr = []
end
def size
arr.size
end
def empty?
arr.empty?
end
def insert(val)
arr << val
heapify_up(arr.size - 1)
end
def top
return if empty?
arr.first
end
def remove_top
return if empty?
swap(0, arr.size - 1)
top = arr.pop
heapify_down(0)
top
end
def swap(idx, other_idx)
arr[idx], arr[other_idx] = arr[other_idx], arr[idx]
end
def compare(idx1, idx2)
self.comparator[arr[idx1], arr[idx2]]
end
def parent(idx)
(idx - 1) / 2
end
def left(idx)
2 * idx + 1
end
def right(idx)
2 * idx + 2
end
def heapify_up(idx)
return if idx.zero?
parent_idx = parent(idx)
if compare(idx, parent_idx)
swap(idx, parent_idx)
heapify_up(parent_idx)
end
end
def heapify_down(idx)
return if idx > arr.length / 2
top_idx = idx
left_idx = left(idx)
right_idx = right(idx)
if left_idx < arr.size && compare(left_idx, top_idx)
top_idx = left_idx
end
if right_idx < arr.size && compare(right_idx, top_idx)
top_idx = right_idx
end
if top_idx != idx
swap(idx, top_idx)
heapify_down(top_idx)
end
end
end
puts "With heap"
def top_k_numbers(nums, k)
pq = Heap.new { |a, b| a < b }
0.upto(nums.length - 1) do |idx|
if idx >= k && pq.top < nums[idx]
pq.remove_top
pq.insert(nums[idx])
elsif idx < k
pq.insert(nums[idx])
end
end
pq.arr
end
p top_k_numbers [3, 1, 5, 12, 2, 11], 3
p top_k_numbers [5, 12, 11, -1, 12], 3
puts "With partitioning"
def partition(nums, pivot = 0, first = 0, last = nums.length - 1)
nums[pivot], nums[first] = nums[first], nums[pivot]
low, high, cur = first + 1, last, first + 1
while cur <= high
if nums[cur] < nums[first]
nums[cur], nums[high] = nums[high], nums[cur]
high -= 1
elsif nums[cur] > nums[first]
nums[cur], nums[low] = nums[low], nums[cur]
low += 1
cur += 1
else
cur += 1
end
end
nums[first], nums[low - 1] = nums[low - 1], nums[first]
high
end
def top_k_numbers(nums, k, first = 0, last = nums.length - 1)
return nums[0..first] if first == last
original_pivot = pivot = partition(nums, first, first, last)
pivot -= 1 while pivot > k - 1 && nums[pivot] == nums[pivot - 1]
if pivot == k - 1
nums[0..pivot]
elsif k > original_pivot
top_k_numbers(nums, k, original_pivot + 1, last)
else
top_k_numbers(nums, k, first, pivot - 1)
end
end
p top_k_numbers [3, 1, 5, 12, 2, 11], 3
p top_k_numbers [5, 12, 11, -1, 12], 3
puts "Kth smallest number"
puts "with heap"
def kth_smallest_number(nums, k)
pq = Heap.new { |a, b| a > b }
nums.each_with_index do |num, idx|
if idx < k
pq.insert(num)
elsif num < pq.top
pq.remove_top
pq.insert(num)
end
end
pq.top
end
p kth_smallest_number [1, 5, 12, 2, 11, 5], 3
p kth_smallest_number [1, 5, 12, 2, 11, 5], 4
p kth_smallest_number [5, 12, 11, -1, 12], 3
puts "with_partitioning"
def partition(nums, pivot = 0, first = 0, last = nums.length - 1)
nums[pivot], nums[first] = nums[first], nums[pivot]
low, high, cur = first + 1, last, first + 1
while cur <= high
if nums[cur] > nums[first]
nums[cur], nums[high] = nums[high], nums[cur]
high -= 1
elsif nums[cur] < nums[first]
nums[cur], nums[low] = nums[low], nums[cur]
low += 1
cur += 1
else
cur += 1
end
end
nums[first], nums[low - 1] = nums[low - 1], nums[first]
high
end
def kth_smallest_number(nums, k, first = 0, last = nums.length - 1)
return nums[first] if first == last
original_pivot = pivot = partition(nums, first, first, last)
pivot -= 1 while pivot > k - 1 && nums[pivot] == nums[pivot - 1]
if pivot == k - 1
nums[pivot]
elsif k > original_pivot
kth_smallest_number(nums, k, original_pivot + 1, last)
else
kth_smallest_number(nums, k, first, pivot - 1)
end
end
p kth_smallest_number [1, 5, 12, 2, 11, 5], 3
p kth_smallest_number [1, 5, 12, 2, 11, 5], 4
p kth_smallest_number [5, 12, 11, -1, 12], 3
puts "K closest points to the origin"
def dist(x, y)
x ** x + y ** y
end
def k_closest_points(points, k)
pq = Heap.new { |p1, p2| dist(*p1) > dist(*p2) }
points.each_with_index do |point, idx|
distance = dist(*point)
if idx < k
pq.insert(point)
elsif distance < dist(*pq.top)
pq.remove_top
pq.insert(point)
end
end
pq.arr
end
p k_closest_points(points = [[1, 2], [1, 3]], 1)
p k_closest_points(points = [[1, 3], [3, 4], [2, -1]], 2)
puts "Connecting ropes"
def connect_ropes(ropes)
pq = Heap.new { |l1, l2| l1 < l2 }
ropes.each do |r|
pq.insert(r)
end
len = pq.remove_top
cost = 0
while !pq.empty?
len += pq.remove_top
cost += len
end
cost
end
p connect_ropes [1, 3, 11, 5]
p connect_ropes [1, 3, 11, 5, 2]
puts "Top k frequent"
def top_k_frequent_numbers(nums, k)
freq_map = Hash.new(0)
nums.each { |num| freq_map[num] += 1 }
pq = Heap.new { |p, q| freq_map[p] < freq_map[q] }
nums = freq_map.keys
0.upto(nums.length - 1) do |idx|
if idx < k
pq.insert(nums[idx])
elsif freq_map[nums[idx]] > freq_map[pq.top]
pq.remove_top
pq.insert(nums[idx])
end
end
pq.arr
end
p top_k_frequent_numbers [1, 3, 5, 12, 11, 12, 11], 2
p top_k_frequent_numbers [5, 12, 11, 3, 11], 2
p top_k_frequent_numbers [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5], 2
puts "Frequency sort"
def freq_sort(str)
freq_map = Hash.new(0)
str.each_char { |c| freq_map[c] += 1 }
pq = Heap.new { |c1, c2| freq_map[c1] > freq_map[c2] }
freq_map.each { |c, _| pq.insert(c) }
res = ""
while !pq.empty?
chr = pq.remove_top
res << chr * freq_map[chr]
end
res
end
p freq_sort "Programming"
p freq_sort "abcbab"
puts "Kth largest in a stream"
def kth_largest_in_stream(nums, k)
pq = Heap.new { |a, b| a < b }
nums.each do |num|
if pq.size < k
pq.insert(num)
elsif num > pq.top
pq.remove_top
pq.insert(num)
end
end
pq.top
end
p kth_largest_in_stream [3, 1, 5, 12, 2, 11], K = 4
puts "K closest numbers"
def k_closest_numbers(nums, k, x)
pq = Heap.new { |a, b| (a - x).abs > (b - x).abs }
nums.each do |num|
if pq.size < k
pq.insert(num)
elsif (num - x).abs < (pq.top - x).abs
pq.remove_top
pq.insert(num)
end
end
pq.arr
end
p k_closest_numbers [5, 6, 7, 8, 9], 3, 7
p k_closest_numbers [2, 4, 5, 6, 9], 3, 10
puts "K closest numbers in a sorted array"
def find_closest(arr, target)
first, last = 0, arr.length - 1
return 0 if target < arr[0]
return arr.length - 1 if target > arr[-1]
while first <= last
mid = (first + last) / 2
return mid if arr[mid] == target
if arr[mid] > target
last = mid - 1
else
first = mid + 1
end
end
(arr[first] - target).abs < (arr[last] - target).abs ? first : last
end
def k_closest_numbers(arr, k, x)
closest_idx = find_closest(arr, x)
pq = Heap.new { |a, b| a < b }
first, last = [0, closest_idx - k].max, [closest_idx + k, arr.length - 1].min
first.upto(last) do |idx|
num = arr[idx]
if pq.size < k
pq.insert(num)
elsif (num - x).abs < (pq.top - x).abs
pq.remove_top
pq.insert(num)
end
end
pq.arr.sort
end
p k_closest_numbers [5, 6, 7, 8, 9], 3, 7
p k_closest_numbers [2, 4, 5, 6, 9], 3, 10
p k_closest_numbers [1, 2, 2, 2, 5, 5, 5, 8, 9, 9], 4, 0
p k_closest_numbers [0, 0, 1, 2, 3, 3, 4, 7, 7, 8], 3, 5
puts "Maximum distinct numbers"
def max_distinct_numbers(nums, k)
freq_map = Hash.new(0)
nums.each { |num| freq_map[num] += 1 }
pq = Heap.new { |a, b| freq_map[a] < freq_map[b] }
freq_map.each { |num, freq| pq.insert(num) if freq > 1 }
while !pq.empty? && k > 0
lowest_fre_elem = pq.remove_top
if k >= freq_map[lowest_fre_elem] - 1
k -= freq_map[lowest_fre_elem] - 1
freq_map[lowest_fre_elem] = 1
else
freq_map[lowest_fre_elem] -= k
k = 0
end
end
uniq_nums = freq_map.keys.select { |num| freq_map[num] == 1 }
uniq_nums.slice(0, uniq_nums.length - k)
end
p max_distinct_numbers [7, 3, 5, 8, 5, 3, 3], 2
p max_distinct_numbers [3, 5, 12, 11, 12], 3
p max_distinct_numbers [1, 2, 3, 3, 3, 3, 4, 4, 5, 5, 5], 2
puts "Sum of numbers between k1th and k2th smallest numbers in array"
def sum_between_smallest(nums, k1, k2)
pq = Heap.new { |a, b| a > b }
sum = 0
nums.each do |num|
if pq.size < k2 - 1
pq.insert(num)
elsif num < pq.top
pq.remove_top
pq.insert(num)
end
end
sum += pq.remove_top while pq.size > k1
sum
end
p sum_between_smallest [1, 3, 12, 5, 15, 11], 3, 6
p sum_between_smallest [3, 5, 8, 7], 1, 4
def sum_between_smallest(nums, k1, k2)
k1_pq = Heap.new { |a, b| a > b }
k2_pq = Heap.new { |a, b| a > b }
sum = 0
nums.each do |num|
inserted = false
if k1_pq.size < k1
inserted = true
k1_pq.insert(num)
elsif num < k1_pq.top
removed_num = k1_pq.remove_top
k1_pq.insert(num)
num = removed_num
end
next if inserted
if k2_pq.size < k2 - k1 - 1
sum += num
k2_pq.insert(num)
elsif num < k2_pq.top
sum += num - k2_pq.remove_top
k2_pq.insert(num)
end
end
sum
end
p sum_between_smallest [1, 3, 12, 5, 15, 11], 3, 6
p sum_between_smallest [3, 5, 8, 7], 1, 4
puts "Rearrange String"
def rearrange_string(str)
freq_map = Hash.new(0)
str.each_char { |c| freq_map[c] += 1 }
pq = Heap.new { |a, b| freq_map[a] > freq_map[b] }
freq_map.each { |c, _| pq.insert(c) }
res = ""
while !pq.empty?
most_frequent = pq.remove_top
if !pq.empty?
second_most_frequent = pq.remove_top
res += "#{most_frequent}#{second_most_frequent}" * freq_map[second_most_frequent]
freq_map[most_frequent] -= freq_map[second_most_frequent]
freq_map.delete(second_most_frequent)
if freq_map[most_frequent].zero?
freq_map.delete(most_frequent)
else
pq.insert(most_frequent)
end
elsif freq_map[most_frequent] > 1
return ""
else
res += most_frequent
end
end
res
end
p rearrange_string "aappp"
p rearrange_string "Programming"
p rearrange_string "aapa"
puts "Rearrange string k distance apart"
def rearrange_string_k_apart(str, k)
freq_map, res = Hash.new(0), ""
str.each_char { |c| freq_map[c] += 1 }
pq = Heap.new { |a, b| freq_map[a] > freq_map[b] }
freq_map.each { |c, _| pq.insert(c) }
queue = []
while !pq.empty?
top = pq.remove_top
res << top
queue << top
if queue.size >= k
first = queue.shift
if freq_map[first].zero?
freq_map.delete(first)
else
pq.insert(first)
end
end
end
res.length == str.length ? res : ""
end
p rearrange_string_k_apart "abcdefg", 20
p rearrange_string_k_apart "mmpp", 2
p rearrange_string_k_apart "Programming", 3
p rearrange_string_k_apart "aab", 2
p rearrange_string_k_apart "aappa", 3
p rearrange_string_k_apart s = "aaadbbcc", 2
p rearrange_string_k_apart "aabbcc", 2
p rearrange_string_k_apart "a", 2
p rearrange_string_k_apart "aa", 0
puts "Scheduling tasks"
def schedule_tasks(tasks, k)
freq_map = Hash.new(0)
tasks.each { |t| freq_map[t] += 1 }
pq = Heap.new { |t1, t2| freq_map[t1] > freq_map[t2] }
freq_map.each { |t, _| pq.insert(t) }
queue, cycles = [], 0
while !freq_map.empty?
if pq.empty?
queue << nil
else
task = pq.remove_top
freq_map[task] -= 1
if freq_map[task].zero?
freq_map.delete(task)
queue << nil
else
queue << task
end
end
if queue.size >= k
first = queue.shift
pq.insert(first) if first
end
cycles += 1
end
cycles
end
p schedule_tasks %w[a a a b c c], 2
p schedule_tasks ["A", "A", "A", "B", "B", "B"], n = 3
p schedule_tasks tasks = ["A", "A", "A", "B", "B", "B"], n = 2
p schedule_tasks tasks = ["A", "A", "A", "B", "B", "B"], n = 50
p schedule_tasks ["A", "A", "A", "A", "A", "A", "B", "C", "D", "E", "F", "G"], 2
def schedule_tasks(tasks, k)
freq_map = Hash.new(0)
tasks.each { |t| freq_map[t] += 1 }
pq = Heap.new { |t1, t2| freq_map[t1] > freq_map[t2] }
freq_map.each { |t, _| pq.insert(t) }
cycles = 0
while !freq_map.empty?
queue = []
n = k
while n > 0 && !pq.empty?
cycles += 1
n -= 1
top_task = pq.remove_top
freq_map[top_task] -= 1
if freq_map[top_task].zero?
freq_map.delete(top_task)
else
queue << top_task
end
end
queue.each { |task| pq.insert(task) }
cycles += n if !freq_map.empty?
end
cycles
end
p schedule_tasks %w[a a a b c c], 2
p schedule_tasks ["A", "A", "A", "B", "B", "B"], n = 3
p schedule_tasks tasks = ["A", "A", "A", "B", "B", "B"], n = 2
p schedule_tasks tasks = ["A", "A", "A", "B", "B", "B"], n = 50
p schedule_tasks ["A", "A", "A", "A", "A", "A", "B", "C", "D", "E", "F", "G"], 2
puts "Frequency Stack"
puts "Using single heap"
class FreqStack
attr_accessor :pq, :freq_map, :counter
def initialize()
self.pq = Heap.new do |(_, freq1, counter1), (_, freq2, counter2)|
if freq1 == freq2
counter1 > counter2
else
freq1 > freq2
end
end
self.counter = 0
self.freq_map = Hash.new(0)
end
def push(num)
self.freq_map[num] += 1
self.counter += 1
pq.insert([num, freq_map[num], self.counter])
end
def pop
num, freq, _ = pq.remove_top
freq_map[num] -= 1
num
end
end
fq = FreqStack.new
input = ["FreqStack", "push", "push", "push", "push", "push", "push", "pop", "pop", "pop", "pop"]
input_vals = [[], [5], [7], [5], [7], [4], [5], [], [], [], []]
outputs = [nil, nil, nil, nil, nil, nil, nil, 5, 7, 5, 4]
1.upto(input.length - 1) do |idx|
if input[idx] == "push"
fq.push(input_vals[idx][0])
else
puts fq.pop
end
end
puts "Using linked lists for each freq"
class FreqStack
class ListNode < Struct.new(:val, :freq, :prev, :next)
end
attr_accessor :node_map, :pq, :node_lists
def initialize
self.node_map = {}
self.node_lists = {}
self.pq = Heap.new { |a, b| a > b }
end
def push(num)
self.node_map[num] ||= ListNode.new(num, 0)
node = self.node_map[num]
remove_from_list(node)
node.freq += 1
if pq.empty? || pq.top < node.freq
pq.insert(node.freq)
end
append_to_tail(node)
end
def pop
top_freq = pq.top
if node_lists[top_freq].prev
node = node_lists[top_freq].prev
remove_from_list(node_lists[top_freq].prev)
node.freq -= 1
append_to_tail(node) if node.freq > 0
if !node_lists[top_freq].prev
node_lists.delete(top_freq)
pq.remove_top
end
return node.val
end
end
private
def remove_from_list(node)
if node.next
node.next.prev = node.prev
node.prev.next = node.next if node.prev
end
node.next = nil
node.prev = nil
end
def append_to_tail(node)
freq = node.freq
node_lists[freq] ||= ListNode.new
tail = node_lists[freq]
node.prev = tail.prev
tail.prev.next = node if tail.prev
node.next = tail
tail.prev = node
end
end
class FreqStack
attr_accessor :freq_map, :freq_stacks
def initialize()
self.freq_map = Hash.new(0)
self.freq_stacks = {}
end
def push(num)
freq_map[num] += 1
freq_stacks[freq_map[num]] ||= []
freq_stacks[freq_map[num]].push(num)
end
def pop
top_frequency = freq_stacks.length
num = freq_stacks[top_frequency].pop
freq_map[num] -= 1
if freq_stacks[top_frequency].empty?
freq_stacks.delete(top_frequency)
end
num
end
end
fq = FreqStack.new
input = ["FreqStack", "push", "push", "push", "push", "push", "push", "pop", "pop", "pop", "pop"]
input_vals = [[], [5], [7], [5], [7], [4], [5], [], [], [], []]
outputs = [nil, nil, nil, nil, nil, nil, nil, 5, 7, 5, 4]
1.upto(input.length - 1) do |idx|
if input[idx] == "push"
fq.push(input_vals[idx][0])
else
puts fq.pop
end
end