Advertisement
hoangreal

minimum number of subsequences of 'source' required to form 'target'

Oct 18th, 2024
32
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.97 KB | Source Code | 0 0
  1. """
  2. Finds the minimum number of subsequences of 'source' required to form 'target'.
  3. Returns -1 if 'target' cannot be formed from 'source'.
  4. """
  5. def solve(source: str, target: str) -> int:
  6.     """
  7.    Time Complexity: O(len(source) * len(target))
  8.    Space Complexity: O(1)
  9.    """
  10.     answer = 0
  11.    
  12.     # Greedy, match as many as you can
  13.     def match_subsequence(source_idx: int, target_idx: int) -> int:
  14.         while source_idx < len(source) and target_idx < len(target):
  15.             if source[source_idx] == target[target_idx]:
  16.                 target_idx += 1
  17.             source_idx += 1 # subsequence -> able to skip it
  18.         return target_idx
  19.  
  20.    
  21.     target_idx = 0
  22.     while target_idx < len(target):
  23.         new_target_idx = match_subsequence(0, target_idx)
  24.        
  25.         if new_target_idx == target_idx:
  26.             answer = -1
  27.             break
  28.         else:
  29.             target_idx = new_target_idx
  30.             answer += 1
  31.  
  32.     return answer
Tags: pinterest
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement