Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to balance the direction string so that each direction occurred quarter times in Python
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 the last N to E, all directions will be there twice.
Algorithm
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 directions that exceed quarter frequency
- for each pair (dir, cnt) in count, do
- if cnt > quarter, then target[dir] := quarter - cnt
- if target is empty, then return 0
- Use sliding window technique to find minimum substring length
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 (direction, cnt) in count.items():
if cnt > quarter:
target[direction] = quarter - cnt
if not target:
return 0
left, min_len = 0, float("inf")
for right, direction in enumerate(s):
if direction in target:
target[direction] += 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
# Test the function
s = "NNSWWESN"
print(f"Input: {s}")
print(f"Output: {solve(s)}")
Input: NNSWWESN Output: 1
How It Works
The algorithm uses a sliding window approach to find the minimum substring that needs to be modified:
- First, it counts the frequency of each direction
- Identifies directions that exceed the quarter limit (n/4)
- Uses a sliding window to find the shortest substring containing excess occurrences
- The target dictionary tracks how many excess characters need to be replaced
Step-by-Step Trace
For input "NNSWWESN" ?
from collections import Counter
s = "NNSWWESN"
n = len(s) # 8
quarter = n // 4 # 2
count = Counter(s)
print("Character frequencies:", dict(count))
# Find excess characters
target = {}
for direction, cnt in count.items():
if cnt > quarter:
target[direction] = quarter - cnt
print("Target (excess to remove):", target)
Character frequencies: {'N': 3, 'S': 2, 'W': 2, 'E': 1}
Target (excess to remove): {'N': -1}
Conclusion
This solution efficiently finds the minimum substring to modify using a sliding window technique. The algorithm ensures each direction appears exactly n/4 times by identifying and targeting excess occurrences.
