# Arrange array elements such that last digit of an element is equal to first digit of the next element

Given an array arr[] of integers, the task is to arrange the array elements such that the last digit of an element is equal to first digit of the next element.

Examples:

Input: arr[] = {123, 321}
Output: 123 321

Input: arr[] = {451, 378, 123, 1254}
Output: 1254 451 123 378

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Naive approach: Find all the permutations of the array elements and then print the arranged array which meets the required condition. The time complexity of this approach is O(N!)

Efficient approach: Create a directed graph where there will be a directed edge from a node A to node B if the last digit of the number represented by Node A is equal to the first digit of the number represented by Node B. Now, find the Eulerian path for the graph formed. The complexity of the above algorithm is O(E * E) where E is the number of edges in the graph.

Below is the implementation of the above approach:

 `// C++ implementation of the approach ` `#include ` `using` `namespace` `std; ` ` `  `// To store the array elements ` `vector arr; ` ` `  `// Adjacency list for the graph nodes ` `vector > graph; ` ` `  `// To store the euler path ` `vector path; ` ` `  `// Print eulerian path ` `bool` `print_euler(``int` `i, ``int` `visited[], ``int` `count) ` `{ ` `    ``// Mark node as visited ` `    ``// and increase the count ` `    ``visited[i] = 1; ` `    ``count++; ` ` `  `    ``// If all the nodes are visited ` `    ``// then we have traversed the euler path ` `    ``if` `(count == graph.size()) { ` `        ``path.push_back(arr[i]); ` `        ``return` `true``; ` `    ``} ` ` `  `    ``// Check if the node lies in euler path ` `    ``bool` `b = ``false``; ` ` `  `    ``// Traverse through remaining edges ` `    ``for` `(``int` `j = 0; j < graph[i].size(); j++) ` `        ``if` `(visited[graph[i][j]] == 0) { ` `            ``b |= print_euler(graph[i][j], visited, count); ` `        ``} ` ` `  `    ``// If the euler path is found ` `    ``if` `(b) { ` `        ``path.push_back(arr[i]); ` `        ``return` `true``; ` `    ``} ` ` `  `    ``// Else unmark the node ` `    ``else` `{ ` `        ``visited[i] = 0; ` `        ``count--; ` `        ``return` `false``; ` `    ``} ` `} ` ` `  `// Function to create the graph and ` `// print the required path ` `void` `connect() ` `{ ` `    ``int` `n = arr.size(); ` `    ``graph.clear(); ` `    ``graph.resize(n); ` ` `  `    ``// Connect the nodes ` `    ``for` `(``int` `i = 0; i < n; i++) { ` `        ``for` `(``int` `j = 0; j < n; j++) { ` `            ``if` `(i == j) ` `                ``continue``; ` ` `  `            ``// If the last character matches with the ` `            ``// first character ` `            ``if` `(arr[i][arr[i].length() - 1] == arr[j]) { ` `                ``graph[i].push_back(j); ` `            ``} ` `        ``} ` `    ``} ` ` `  `    ``// Print the path ` `    ``for` `(``int` `i = 0; i < n; i++) { ` `        ``int` `visited[n] = { 0 }, count = 0; ` ` `  `        ``// If the euler path starts ` `        ``// from the ith node ` `        ``if` `(print_euler(i, visited, count)) ` `            ``break``; ` `    ``} ` ` `  `    ``// Print the euler path ` `    ``for` `(``int` `i = path.size() - 1; i >= 0; i--) { ` `        ``cout << path[i]; ` `        ``if` `(i != 0) ` `            ``cout << ``" "``; ` `    ``} ` `} ` `// Driver code ` `int` `main() ` `{ ` `    ``arr.push_back(``"451"``); ` `    ``arr.push_back(``"378"``); ` `    ``arr.push_back(``"123"``); ` `    ``arr.push_back(``"1254"``); ` ` `  `    ``// Create graph and print the path ` `    ``connect(); ` ` `  `    ``return` `0; ` `} `

 `# Python3 implementation of the approach  ` ` `  `# Print eulerian path  ` `def` `print_euler(i, visited, count):  ` ` `  `    ``# Mark node as visited  ` `    ``# and increase the count  ` `    ``visited[i] ``=` `1` `    ``count ``+``=` `1` ` `  `    ``# If all the nodes are visited then  ` `    ``# we have traversed the euler path  ` `    ``if` `count ``=``=` `len``(graph):  ` `        ``path.append(arr[i])  ` `        ``return` `True` `     `  `    ``# Check if the node lies in euler path  ` `    ``b ``=` `False` ` `  `    ``# Traverse through remaining edges  ` `    ``for` `j ``in` `range``(``0``, ``len``(graph[i])):  ` `        ``if` `visited[graph[i][j]] ``=``=` `0``:  ` `            ``b |``=` `print_euler(graph[i][j], visited, count)  ` ` `  `    ``# If the euler path is found  ` `    ``if` `b:  ` `        ``path.append(arr[i])  ` `        ``return` `True` `     `  `    ``# Else unmark the node  ` `    ``else``:  ` `        ``visited[i] ``=` `0` `        ``count ``-``=` `1` `        ``return` `False` `     `  `# Function to create the graph  ` `# and print the required path  ` `def` `connect():  ` ` `  `    ``n ``=` `len``(arr) ` `    ``# Connect the nodes  ` `    ``for` `i ``in` `range``(``0``, n):  ` `        ``for` `j ``in` `range``(``0``, n):  ` `            ``if` `i ``=``=` `j:  ` `                ``continue` ` `  `            ``# If the last character matches  ` `            ``# with the first character  ` `            ``if` `arr[i][``-``1``] ``=``=` `arr[j][``0``]:  ` `                ``graph[i].append(j)  ` ` `  `    ``# Print the path  ` `    ``for` `i ``in` `range``(``0``, n):  ` `        ``visited ``=` `[``0``] ``*` `n ` `        ``count ``=` `0` ` `  `        ``# If the euler path starts  ` `        ``# from the ith node  ` `        ``if` `print_euler(i, visited, count):  ` `            ``break` `     `  `    ``# Print the euler path  ` `    ``for` `i ``in` `range``(``len``(path) ``-` `1``, ``-``1``, ``-``1``):  ` `        ``print``(path[i], end ``=` `"")  ` `        ``if` `i !``=` `0``: ` `            ``print``(``" "``, end ``=` `"")  ` `     `  `# Driver code  ` `if` `__name__ ``=``=` `"__main__"``: ` `     `  `    ``# To store the array elements  ` `    ``arr ``=` `[] ` `    ``arr.append(``"451"``)  ` `    ``arr.append(``"378"``)  ` `    ``arr.append(``"123"``)  ` `    ``arr.append(``"1254"``) ` `     `  `    ``# Adjacency list for the graph nodes ` `    ``graph ``=` `[[] ``for` `i ``in` `range``(``len``(arr))] ` `     `  `    ``# To store the euler path ` `    ``path ``=` `[] ` ` `  `    ``# Create graph and print the path  ` `    ``connect() ` ` `  `# This code is contributed by Rituraj Jain `

Output:
```1254 451 123 378
```

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Improved By : rituraj_jain

Article Tags :
Practice Tags :