Generating random strings until a given string is generated

Last Updated : 2 Feb, 2026

Given a target string 'S', the task is to generate random strings of the same length as 'S' until the generated string exactly matches the target. For Example:

Input: hello

Output:
jfus
flsf
sowe
hello
Target matched after 3 iterations

Let's look at the different methods below:

Genetic Algorithm

This approach starts with a random string and slowly evolves it toward the target string. It changes one character at a time and only keeps changes that make the string closer to the target.

Python
import string
import random

chars = string.ascii_letters + string.digits + ' .,!?;:'
target = "geeks"

s = ''.join(random.choice(chars) for _ in range(len(target)))
iterations = 0

while s != target:
    print(s) 

    i = random.randint(0, len(s)-1)
    l = list(s)
    l[i] = random.choice(chars)
    s1 = ''.join(l)

    if sum(a == b for a, b in zip(s1, target)) >= sum(a == b for a, b in zip(s, target)):
        s =