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 nth sequence after following the given string sequence rules in Python
Suppose we have two strings s, t and another positive number n is also given, we have to find the nth term of the sequence A where:
- A[0] = s
- A[1] = t
- A[n] = A[n - 1] + A[n - 2] when n is even, otherwise A[n] = A[n - 2] + A[n - 1]
As an example, if s = "a" and t = "b", then the sequence A would be: ["a", "b", "ba" ("b" + "a"), "bba" ("b" + "ba"), "bbaba" ("bba" + "ba")]
So, if the input is like s = "pk", t = "r", n = 4, then the output will be "rrpkrpk"
Algorithm
To solve this, we will follow these steps:
- If n is 0, return s
- If n is 1, return t
- Initialize a = s, b = t
- For i from 2 to n:
- If i is even, concatenate: c = b + a
- If i is odd, concatenate: c = a + b
- Update: a = b, b = c
- Return c
Example
class Solution:
def solve(self, s, t, n):
if n == 0:
return s
elif n == 1:
return t
a = s
b = t
for i in range(2, n + 1):
if i % 2 == 0:
c = b + a
else:
c = a + b
a = b
b = c
return c
# Test the solution
ob = Solution()
print(ob.solve("pk", "r", 4))
rrpkrpk
Step-by-Step Execution
Let's trace through the example with s = "pk", t = "r", n = 4:
def trace_sequence(s, t, n):
print(f"A[0] = {s}")
print(f"A[1] = {t}")
if n <= 1:
return
a, b = s, t
for i in range(2, n + 1):
if i % 2 == 0:
c = b + a
print(f"A[{i}] = A[{i-1}] + A[{i-2}] = {b} + {a} = {c}")
else:
c = a + b
print(f"A[{i}] = A[{i-2}] + A[{i-1}] = {a} + {b} = {c}")
a, b = b, c
trace_sequence("pk", "r", 4)
A[0] = pk A[1] = r A[2] = A[1] + A[0] = r + pk = rpk A[3] = A[1] + A[2] = r + rpk = rrpk A[4] = A[3] + A[2] = rrpk + rpk = rrpkrpk
Alternative Implementation
Here's a more compact version without using a class:
def find_nth_sequence(s, t, n):
if n == 0:
return s
if n == 1:
return t
prev2, prev1 = s, t
for i in range(2, n + 1):
if i % 2 == 0:
current = prev1 + prev2
else:
current = prev2 + prev1
prev2, prev1 = prev1, current
return current
# Test cases
test_cases = [
("pk", "r", 4),
("a", "b", 3),
("x", "y", 0),
("hello", "world", 2)
]
for s, t, n in test_cases:
result = find_nth_sequence(s, t, n)
print(f"s='{s}', t='{t}', n={n} ? '{result}'")
s='pk', t='r', n=4 ? 'rrpkrpk' s='a', t='b', n=3 ? 'ab' s='x', t='y', n=0 ? 'x' s='hello', t='world', n=2 ? 'worldhello'
Conclusion
This problem follows a modified Fibonacci-like pattern where string concatenation order depends on whether the index is even or odd. The solution uses iterative approach with O(n) time complexity to build the sequence step by step.
