Program to find out the letter at a particular index in a synthesized string in python

Suppose, we are given a string input_str. We need to find all possible substrings from the given string, then concatenate all the substrings in lexicographic order into another string. Given an integer value k, our task is to return the letter at index k from the concatenated string.

So, if the input is like input_str = 'pqrs', k = 6, then the output will be 'p'.

Understanding the Problem

The substrings from the given string 'pqrs' in lexicographic order are: p, pq, pqr, pqrs, q, qr, qrs, r, rs, s.

If we concatenate these strings, it becomes: ppqpqrpqrsqqrqrsrrss. At position 6 (0-indexed), the letter is 'p'.

Algorithm

To solve this problem, we will follow these steps:

  • Create a stack containing a tuple with an empty string and indices of all characters
  • While the stack is not empty:
    • Pop the last element from the stack
    • If k is less than the length of the current prefix, return the character at position k
    • Otherwise, reduce k by the length of the current prefix
    • Sort the remaining characters lexicographically and add them to the stack

Example

Let us see the following implementation to get better understanding:

def solve(input_str, k):
    stk_list = [("", list(range(len(input_str))))]
    
    while stk_list:
        pre, temp = stk_list.pop()
        
        if k < len(pre):
            return pre[k]
        
        k -= len(pre)
        input_sorted = sorted([(input_str[i], i+1) for i in temp if i < len(input_str)], reverse=True)
        
        i = 0
        while i < len(input_sorted):
            val = input_sorted[i][0]
            temp1 = [input_sorted[i][1]]
            j = i + 1
            
            while j < len(input_sorted) and input_sorted[j][0] == val:
                temp1.append(input_sorted[j][1])
                j += 1
            
            stk_list.append((pre + val, temp1))
            i = j
    
    return None

# Test the function
result = solve('pqrs', 6)
print(f"Character at index 6: {result}")
Character at index 6: p

How It Works

The algorithm uses a stack-based approach to generate substrings in lexicographic order without actually creating the full concatenated string. It processes characters by:

  • Starting with an empty prefix and all character positions
  • For each iteration, checking if the target index k falls within the current prefix
  • If not, it reduces k and continues with the next lexicographic combinations
  • This approach is memory-efficient as it doesn't store the entire concatenated string

Alternative Simple Approach

For better understanding, here's a simpler approach that generates all substrings:

def solve_simple(input_str, k):
    # Generate all substrings
    substrings = []
    n = len(input_str)
    
    for i in range(n):
        for j in range(i + 1, n + 1):
            substrings.append(input_str[i:j])
    
    # Sort lexicographically
    substrings.sort()
    
    # Concatenate all substrings
    concatenated = ''.join(substrings)
    
    # Return character at index k
    return concatenated[k] if k < len(concatenated) else None

# Test the function
result = solve_simple('pqrs', 6)
print(f"Character at index 6: {result}")
print(f"All substrings: {sorted([input_str[i:j] for i in range(len('pqrs')) for j in range(i+1, len('pqrs')+1)])}")
Character at index 6: p
All substrings: ['p', 'pq', 'pqr', 'pqrs', 'q', 'qr', 'qrs', 'r', 'rs', 's']

Conclusion

The stack-based solution efficiently finds the character at a specific index without generating the entire concatenated string, making it memory-efficient for large inputs. The simple approach helps understand the problem better by showing all substrings explicitly.

Updated on: 2026-03-26T15:23:41+05:30

177 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements