Check if a two-character string can be made using given words in Python

Suppose we have a string s of length 2, and also have a list of words w where all words are of length 2. We have to check whether we can concatenate words from w and that concatenated string contains s as substring or not.

So, if the input is like s = "no", w = ["ol", "on", "ni", "to"], then the output will be True as we can concatenate strings like "onol", that contains "no"

To solve this, we will follow these steps −

  • n := the number of words in w
  • char_0 := False, char_1 := False
  • for i in range 0 to n - 1, do
    • if w[i] is same as s, then
      • return True
    • if s[0] is same as w[i, 1], then
      • char_0 := True
    • if s[1] is same as w[i, 0], then
      • char_1 := True
    • if char_0 and char_1 both are true, then
      • return True
  • return False

Let us see the following implementation to get better understanding −


 Live Demo

def solve(s, w):
   n = len(w)
   char_0 = False
   char_1 = False
   for i in range(n):
      if w[i] == s:
         return True
      if s[0] == w[i][1]:
         char_0 = True
      if s[1] == w[i][0]:
         char_1 = True
      if char_0 and char_1:
         return True
   return False
s = "no"
w = ["ol", "on", "ni", "to"]
print(solve(s, w))


"no", ["ol", "on", "ni", "to"]