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
Check if a two-character string can be made using given words in Python
Given a two-character string s and a list of two-character words w, we need to check whether we can concatenate words from w to create a string that contains s as a substring.
For example, if s = "no" and w = ["ol", "on", "ni", "to"], we can concatenate "on" + "ol" to get "onol", which contains "no" as a substring.
Algorithm
To solve this problem, we need to check three possible scenarios ?
- The target string
sexists directly in the word list - We can form
sby taking the second character of one word and the first character of another word - We can form
sby concatenating two words wheresappears as a substring
Implementation
def solve(s, w):
n = len(w)
char_0 = False # Can we find s[0] as the second character of any word?
char_1 = False # Can we find s[1] as the first character of any word?
for i in range(n):
# Check if the target string exists directly
if w[i] == s:
return True
# Check if s[0] matches the second character of word w[i]
if s[0] == w[i][1]:
char_0 = True
# Check if s[1] matches the first character of word w[i]
if s[1] == w[i][0]:
char_1 = True
# If both conditions are met, we can form the substring
if char_0 and char_1:
return True
return False
# Test the function
s = "no"
w = ["ol", "on", "ni", "to"]
result = solve(s, w)
print(f"Can form '{s}' using words {w}: {result}")
Can form 'no' using words ['ol', 'on', 'ni', 'to']: True
How It Works
The algorithm works by checking if we can find the target substring in any possible concatenation ?
- Direct match: If any word in the list equals our target string, return True immediately
- Cross-boundary match: Look for cases where the first character of our target appears as the second character of one word, and the second character appears as the first character of another word
- Early termination: As soon as both conditions are satisfied, we can return True
Example Walkthrough
For s = "no" and w = ["ol", "on", "ni", "to"] ?
def solve_with_trace(s, w):
print(f"Looking for substring: '{s}'")
print(f"Available words: {w}")
char_0 = False
char_1 = False
for i, word in enumerate(w):
print(f"\nChecking word '{word}':")
if word == s:
print(f" Direct match found!")
return True
if s[0] == word[1]:
print(f" '{s[0]}' found at position 1 of '{word}'")
char_0 = True
if s[1] == word[0]:
print(f" '{s[1]}' found at position 0 of '{word}'")
char_1 = True
if char_0 and char_1:
print(f" Both characters found - can form '{s}'!")
return True
return False
# Trace through the example
s = "no"
w = ["ol", "on", "ni", "to"]
result = solve_with_trace(s, w)
print(f"\nResult: {result}")
Looking for substring: 'no' Available words: ['ol', 'on', 'ni', 'to'] Checking word 'ol': 'o' found at position 0 of 'ol' Checking word 'on': 'n' found at position 1 of 'on' Both characters found - can form 'no'! Result: True
Time and Space Complexity
- Time Complexity: O(n), where n is the number of words in the list
- Space Complexity: O(1), using only constant extra space
Conclusion
This algorithm efficiently checks if a two-character substring can be formed by concatenating words from a given list. It uses a single pass through the word list and early termination for optimal performance.
