Generate all strings from mid in circular manner

Last Updated : 31 May, 2026

Given an odd length string s, return a list of strings by starting from the middle character of s and then repeatedly appending the next characters in circular order. Continue this process until all characters of the string have been included.

Examples:

Input: s = "RAT"
Output: ["A", "AT", "ATR"]
Explanation: The middle character of "RAT" is 'A'.
Starting from the middle and appending the next characters in circular order:
A
AT
ATR
Here, after reaching 'T', the traversal wraps around to the beginning of the string and continues with 'R' to complete the pattern sequence.

Input: s = "PROGRAM"
Output: ["G", "GR", "GRA", "GRAM", "GRAMP", "GRAMPR", "GRAMPRO"]
Explanation: The middle character of "PROGRAM" is 'G'.
Starting from 'G', characters are appended one by one in circular order to form the sequence:
G
GR
GRA
GRAM
GRAMP
GRAMPR
GRAMPRO
Here, after reaching 'M', the traversal wraps around to the beginning of the string and continues with 'P', 'R', and 'O' to complete the pattern sequence.

Try It Yourself
redirect icon

[Naive Approach] Build Each Pattern Separately - O(n^2) Time O(n^2) Space

The idea is to find the middle character of the string and generate every pattern separately. For each required pattern length, start from the middle index and traverse the string in circular order, building the pattern from scratch by appending characters one by one.

C++
#include <iostream>
using namespace std;

vector<string> midPattern(string &s)
{
    int n = s.size();
    int mid = n / 2;

    vector<string> res;

    // Generate each pattern independently
    for (int len = 1; len <= n; len++)
    {
        string cur = "";

        // Build the current pattern from scratch
        for (int j = 0; j < len; j++)
        {
            cur += s[(mid + j) % n];
        }

        res.push_back(cur);
    }

    return res;
}

// Driver Code
int main()
{
    string s = "PROGRAM";

    vector<string> res = midPattern(s);

    cout << "[";
    for (int i = 0; i < res.size(); i++)
    {
        cout << "\"" << res[i] << "\"";
        if (i + 1 < res.size())
        {
            cout << ", ";
        }
    }
    cout << "]";

    return 0;
}
Java
import java.util.ArrayList;
import java.util.List;

public class GfG {
    public static List<String> midPattern(String s)
    {
        int n = s.length();
        int mid = n / 2;

        List<String> res = new ArrayList<>();

        // Generate each pattern independently
        for (int len = 1; len <= n; len++) {
            String cur = "";

            // Build the current pattern from scratch
            for (int j = 0; j < len; j++) {
                cur += s.charAt((mid + j) % n);
            }

            res.add(cur);
        }

        return res;
    }

    public static void main(String[] args)
    {
        String s = "PROGRAM";

        List<String> res = midPattern(s);

        System.out.print("[");
        for (int i = 0; i < res.size(); i++) {
            System.out.print("\"" + res.get(i) + "\"");
            if (i + 1 < res.size()) {
                System.out.print(", ");
            }
        }
        System.out.print("]");
    }
}
Python
def midPattern(s):
    n = len(s)
    mid = n // 2

    res = []

    # Generate each pattern independently
    for length in range(1, n + 1):
        cur = ""

        # Build the current pattern from scratch
        for j in range(length):
            cur += s[(mid + j) % n]

        res.append(cur)

    return res


# Driver Code
if __name__ == "__main__":
    s = "PROGRAM"

    res = midPattern(s)

    print('[', end='')
    for i in range(len(res)):
        print(f'"{res[i]}"', end='')
        if i + 1 < len(res):
            print(', ', end='')
    print(']')
C#
using System;
using System.Collections.Generic;

public class GfG {
    public static List<string> midPattern(string s)
    {
        int n = s.Length;
        int mid = n / 2;

        List<string> res = new List<string>();

        // Generate each pattern independently
        for (int len = 1; len <= n; len++) {
            string cur = "";

            // Build the current pattern from scratch
            for (int j = 0; j < len; j++) {
                cur += s[(mid + j) % n];
            }

            res.Add(cur);
        }

        return res;
    }

    public static void Main()
    {
        string s = "PROGRAM";

        List<string> res = midPattern(s);

        Console.Write("[");
        for (int i = 0; i < res.Count; i++) {
            Console.Write("\"" + res[i] + "\"");
            if (i + 1 < res.Count) {
                Console.Write(", ");
            }
        }
        Console.Write("]");
    }
}
JavaScript
function midPattern(s)
{
    const n = s.length;
    const mid = Math.floor(n / 2);

    const res = [];

    // Generate each pattern independently
    for (let len = 1; len <= n; len++) {
        let cur = "";

        // Build the current pattern from scratch
        for (let j = 0; j < len; j++) {
            cur += s[(mid + j) % n];
        }

        res.push(cur);
    }

    return res;
}

// Driver Code
const s = "PROGRAM";
const res = midPattern(s);

console.log("["
            + res.map(item => "\"" + item + "\"").join(", ")
            + "]");

Output
["G", "GR", "GRA", "GRAM", "GRAMP", "GRAMPR", "GRAMPRO"]

Time Complexity: O(n^2)
Auxiliary Space: O(n^2)

[Expected Approach] Using Circular Traversal - O(n^2) Time O(n) Space

The idea is to start from the middle character and traverse the string in circular order while maintaining a running pattern string. In each iteration, append the next character to the current pattern and store the updated pattern in the result. This way, each new pattern is obtained by extending the previous one instead of rebuilding it from scratch, making the construction more efficient.

C++
#include <iostream>
using namespace std;

vector<string> midPattern(string &s)
{
    int n = s.size();
    int mid = n / 2;

    vector<string> res;
    res.reserve(n);

    string cur;
    cur.reserve(n);

    for (int i = 0; i < n; i++)
    {

        // Append characters in circular order starting from the middle
        cur += s[(mid + i) % n];

        // Store the current pattern
        res.push_back(cur);
    }

    return res;
}

// Driver Code
int main()
{
    string s = "PROGRAM";

    vector<string> res = midPattern(s);

    cout << "[";
    for (int i = 0; i < res.size(); i++)
    {
        cout << "\"" << res[i] << "\"";
        if (i + 1 < res.size())
        {
            cout << ", ";
        }
    }
    cout << "]";

    return 0;
}
Java
import java.util.ArrayList;
import java.util.List;

public class GfG {
    public static List<String> midPattern(String s)
    {
        int n = s.length();
        int mid = n / 2;

        List<String> res = new ArrayList<>();

        StringBuilder cur = new StringBuilder();

        for (int i = 0; i < n; i++) {

            // Append characters in circular order starting
            // from the middle
            cur.append(s.charAt((mid + i) % n));

            // Store the current pattern
            res.add(cur.toString());
        }

        return res;
    }

    public static void main(String[] args)
    {
        String s = "PROGRAM";

        List<String> res = midPattern(s);

        System.out.print("[");
        for (int i = 0; i < res.size(); i++) {
            System.out.print("\"" + res.get(i) + "\"");
            if (i + 1 < res.size()) {
                System.out.print(", ");
            }
        }
        System.out.print("]");
    }
}
Python
def midPattern(s):
    n = len(s)
    mid = n // 2

    res = []

    # Generate each pattern independently
    for length in range(1, n + 1):
        cur = ""

        # Build the current pattern from scratch
        for j in range(length):
            cur += s[(mid + j) % n]

        res.append(cur)

    return res


# Driver Code
if __name__ == "__main__":
    s = "PROGRAM"

    res = midPattern(s)

    print('[', end='')
    for i in range(len(res)):
        print(f'"{res[i]}"', end='')
        if i + 1 < len(res):
            print(', ', end='')
    print(']')
C#
using System;
using System.Collections.Generic;
using System.Text;

public class GfG {
    public static List<string> midPattern(string s)
    {
        int n = s.Length;
        int mid = n / 2;

        List<string> res = new List<string>(n);

        StringBuilder cur = new StringBuilder(n);

        for (int i = 0; i < n; i++) {

            // Append characters in circular order starting
            // from the middle
            cur.Append(s[(mid + i) % n]);

            // Store the current pattern
            res.Add(cur.ToString());
        }

        return res;
    }

    public static void Main()
    {
        string s = "PROGRAM";

        List<string> res = midPattern(s);

        Console.Write("[");
        for (int i = 0; i < res.Count; i++) {
            Console.Write("\"" + res[i] + "\"");
            if (i + 1 < res.Count) {
                Console.Write(", ");
            }
        }
        Console.Write("]");
    }
}
JavaScript
// Function to generate the middle pattern
function midPattern(s)
{
    let n = s.length;
    let mid = Math.floor(n / 2);

    let res = [];
    let cur = "";

    for (let i = 0; i < n; i++) {

        // Append characters in circular order starting
        // from the middle
        cur += s[(mid + i) % n];

        // Store the current pattern
        res.push(cur);
    }

    return res;
}

// Driver Code
let s = "PROGRAM";

let res = midPattern(s);

process.stdout.write("[");
for (let i = 0; i < res.length; i++) {
    process.stdout.write(`"${res[i]}"`);
    if (i + 1 < res.length) {
        process.stdout.write(", ");
    }
}
process.stdout.write("]");

Output
["G", "GR", "GRA", "GRAM", "GRAMP", "GRAMPR", "GRAMPRO"]

Time Complexity: O(n^2)
Auxiliary Space: O(n)

Comment