More patterns for coding interviews |||

9- Rearrange string k distance apart

class Solution:
def reorganizeString(self, s):
queue, stack, ans =[(-count,char) for char, count in Counter(s).items()], [], ""
heapify(queue)

while queue:
for _ in range(2):
if not queue and stack: return ""
if queue:
count, char = heappop(queue)
ans += char
if count<-1: stack.append((count+1, char))

while stack: heappush(queue, stack.pop())

return ans
class Solution:
def leastInterval(self, tasks: List[str], n: int) -> int:
time, queue, stack = 0, [(-1*count, char) for char, count in Counter(tasks).items()], []
heapify(queue)

while queue:
for _ in range(n+1):
if queue or stack: time += 1
if queue:
count, char = heappop(queue)
if count<-1: stack.append((count+1,char))

while stack: heappush(queue, stack.pop())

return time
class Solution:
def rearrangeString(self, s, k):
queue, stack, ans =[(-count,char) for char, count in Counter(s).items()], [], ""
heapify(queue)

while queue:
for _ in range(k):
if not queue and stack: return ""
if queue:
count, char = heappop(queue)
ans += char
if count<-1: stack.append((count+1, char))

while stack: heappush(queue, stack.pop())

return ans

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

The Most Valuable Thing You Can Learn in Software Development in 2021

Python Tuples and Tuple Methods

Beginning Python Programming — Part 16

How to find Windows 7/8/10 product key using CMD , PowerShell, Registry

Use Apache Camel K to Create Microservice Apps with Instana

Deploy Backend to Linux Server

A Noob’s Guide to Gluster on ZFS

MongoDB Schema Design Anti-patterns in a Nutshell

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Muhammed Abogazia

Muhammed Abogazia

human

More from Medium

Do not ask this question in Coding Interview

My Software Engineer Interview Questions

Amazon Interview Question — LeetCode 1306 — Y Tech

LeetCode 17 — Letter Combinations of a Phone Number