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 find list that shows closest distance of character c from that index in Python
Given a string s and a character c that exists in the string, we need to find the closest distance from each character position to any occurrence of character c. The result is a list where each element represents the minimum distance from that index to the nearest occurrence of c.
For example, if s = "ppqppq" and c = "q", the output will be [2, 1, 0, 1, 1, 0] because:
Index 0 ('p'): closest 'q' is at index 2, distance = 2
Index 1 ('p'): closest 'q' is at index 2, distance = 1
Index 2 ('q'): distance to itself = 0
Index 3 ('p'): closest 'q' is at index 2 or 5, distance = 1
Index 4 ('p'): closest 'q' is at index 5, distance = 1
Index 5 ('q'): distance to itself = 0
Algorithm Steps
To solve this problem efficiently, we follow these steps ?
Initialize a distance array with maximum possible distances
Find the first occurrence of character c
For each character in the string, update distances based on the nearest c found so far
When we encounter a new occurrence of c, update previous distances if they can be improved
Implementation
def solve(s, c):
j = len(s)
d = [j - 1] * j # Initialize with maximum possible distance
x = s.index(c) # Find first occurrence of c
for i in range(j):
if s[i] == c and i > x:
# Found a new occurrence of c, update previous distances
x = i
ind = 1
while x - ind >= 0:
if d[x - ind] > ind:
d[x - ind] = ind
else:
break
ind += 1
# Update current position with distance to nearest c
d[i] = abs(x - i)
return d
# Test the function
s = "ppqppq"
c = "q"
result = solve(s, c)
print(f"String: {s}")
print(f"Character: {c}")
print(f"Distance array: {result}")
String: ppqppq Character: q Distance array: [2, 1, 0, 1, 1, 0]
How It Works
The algorithm processes the string from left to right:
Initialization: Create a distance array filled with the maximum possible distance (
len(s) - 1)First occurrence: Find the first position of character c in the string
Forward pass: For each position, calculate distance to the rightmost occurrence of c seen so far
Backward update: When finding a new c, update distances for previous positions if they can be improved
Alternative Approach
A simpler two-pass approach can also solve this problem ?
def solve_simple(s, c):
n = len(s)
distances = [float('inf')] * n
# Forward pass: find distances to c on the left
last_c_pos = -float('inf')
for i in range(n):
if s[i] == c:
last_c_pos = i
distances[i] = i - last_c_pos
# Backward pass: find distances to c on the right
last_c_pos = float('inf')
for i in range(n - 1, -1, -1):
if s[i] == c:
last_c_pos = i
distances[i] = min(distances[i], last_c_pos - i)
return distances
# Test both approaches
s = "ppqppq"
c = "q"
print("Original approach:", solve(s, c))
print("Simple approach:", solve_simple(s, c))
Original approach: [2, 1, 0, 1, 1, 0] Simple approach: [2, 1, 0, 1, 1, 0]
Conclusion
Both approaches efficiently find the closest distance to character c from each position. The two-pass method is easier to understand, while the single-pass approach optimizes by updating distances as new occurrences are found.
