Open In App

Find if an array of strings can be chained to form a circle

Last Updated : 19 Apr, 2025
Comments
Improve
Suggest changes
29 Likes
Like
Report

Given an array of strings, the task is to find if the given strings can be chained to form a circle. A string X can be put before another string Y in circle if the last character of X is same as first character of Y.

Examples: 

Input: arr[] = ["geek", "king"]
Output: Yes, the given strings can be chained.
Explanation: Note that the last character of first string is same
as first character of second string and vice versa is also true.

Input: arr[] = ["aaa", "bbb", "baa", "aab"]
Output: Yes, the given strings can be chained.
Explanation: The strings can be chained as "aaa", "aab", "bbb" and "baa"

Input: arr[] = ["aaa"]
Output: Yes

Input: arr[] = ["aaa", "bbb"]
Output: No

Approach:

The idea is to create a directed graph of all characters and then find if there is an eulerian circuit in the graph or not.  If there is an eulerian circuit, then chain can be formed, otherwise not. 

Note that a directed graph has eulerian circuit only if in degree and out degree of every vertex is same, and all non-zero degree vertices form a single strongly connected component.

We solve this problem by treating this as a graph problem, where vertices will be the first and last character of strings, and we will draw an edge between two vertices if they are the first and last character of the same string, so a number of edges in the graph will be same as the number of strings in the array.

Step by step approach:

  1. Create a directed graph where each node represents a letter (a-z) and edges connect first and last letters of words.
  2. For each string, add an edge from its first character to its last character.
  3. Check if the graph is strongly connected (can reach all nodes with non-zero degree from any node).
  4. Verify each node has equal in-degree and out-degree (necessary condition for Eulerian cycle).
  5. If both conditions are met, the strings can be chained in a circle.
C++
Java Python C# JavaScript

Output
Yes

Time Complexity: O(n)
Auxiliary space:  O(n)

Related Article:


Circle of strings | DSA Problem
Practice Tags :

Similar Reads