# Program to balance the direction string so that each direction occurred quarter times in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Suppose we have a string s with four directions "N", "S", "W" and "E" for North, South, West and East respectively. We have to find the size of the shortest substring we can update such that each of the four directions occur n/4 times each, where n is the size of string s.

So, if the input is like s = "NNSWWESN", then the output will be 1, here n is 8, so 8/4 is 2, so if we change last N to E, all directions will be there twice.

To solve this, we will follow these steps −

• n := size of s
• if n is 0, then
• return 0
• quarter := floor of (n / 4)
• count := a list containing frequencies of each elements present in s
• target := a new map
• for each pair (dir, cnt) in count, do
• if cnt > quarter, then
• target[dir] := quarter - cnt
• if target is empty, then
• return 0
• left := 0
• min_len := inf
• for each index right and direction dir in s, do
• if dir is in target, then
• target[dir] := target[dir] + 1
• while minimum of list of all values of target >= 0, do
• min_len := minimum of min_len and (right - left + 1)
• if s[left] in target, then
• target[s[left]] := target[s[left]] - 1
• left := left + 1
• return min_len

## Example

Let us see the following implementation to get better understanding −

from collections import Counter
def solve(s):
n = len(s)

if not n:
return 0
quarter = n // 4

count = Counter(s)
target = dict()
for (dir, cnt) in count.items():
if cnt > quarter:
target[dir] = quarter - cnt

if not target:
return 0

left, min_len = 0, float("inf")
for right, dir in enumerate(s):
if dir in target:
target[dir] += 1

while min(target.values()) >= 0:
min_len = min(min_len, right - left + 1)
if s[left] in target:
target[s[left]] -= 1
left += 1

return min_len

s = "NNSWWESN"
print(solve(s))

## Input

"NNSWWESN"

## Output

1