Program to find length of longest possible stick in Python?

Suppose we have a list of integers representing sticks. Each element in the list represents a stick with two ends, where values are between 1 and 6. We can connect two sticks together if any of their ends are the same. The resulting stick's ends will be the leftover ends and its length is increased. We have to find the length of the longest stick possible.

So, if the input is like sticks = [[2, 3], [2, 4], [3, 5], [6, 6]], then the output will be 3. We can connect [2, 3] and [2, 4] to get [3, 4], then connect it with [3, 5] to get [4, 5].

Approach

This problem can be solved using graph traversal where:

  • Each stick endpoint is a vertex

  • Each stick is an edge connecting two vertices

  • We find the longest path in this graph using DFS

Algorithm Steps

The solution follows these steps:

  1. Build a graph where vertices are stick endpoints and edges represent sticks

  2. Use DFS to explore all possible paths from each vertex

  3. Keep track of visited edges to avoid cycles

  4. Return the maximum path length found

Example

from collections import defaultdict

class Solution:
    def solve(self, sticks):
        def dfs(node, edge_idx, visited):
            if edge_idx is not None:
                if edge_idx in visited:
                    return 0
                visited.add(edge_idx)
            
            res = 0
            for e_idx in g[node]:
                n_node = sticks[e_idx][0] if sticks[e_idx][1] == node else sticks[e_idx][1]
                res = max(res, 1 + dfs(n_node, e_idx, visited))
            
            if edge_idx:
                visited.remove(edge_idx)
            return res

        # Build graph
        vertices = set()
        g = defaultdict(set)
        
        for i, edge in enumerate(sticks):
            g[edge[0]].add(i)
            g[edge[1]].add(i)
            vertices.add(edge[0])
            vertices.add(edge[1])
        
        # Find maximum path from any vertex
        res = 0
        for v in vertices:
            res = max(res, dfs(v, None, set()))
        
        return res - 1

# Test the solution
ob = Solution()
sticks = [
    [2, 3],
    [2, 4], 
    [3, 5],
    [6, 6]
]

print("Input sticks:", sticks)
print("Longest stick length:", ob.solve(sticks))
Input sticks: [[2, 3], [2, 4], [3, 5], [6, 6]]
Longest stick length: 3

How It Works

Let's trace through the example:

  1. Graph Construction: Vertices = {2, 3, 4, 5, 6}, Edges connect matching endpoints

  2. DFS from vertex 2: Can connect [2,3] ? [3,5] ? [4,5] (length 3)

  3. DFS from other vertices: No longer paths found

  4. Result: Maximum length is 3

Key Points

  • Backtracking: We remove edges from visited set to explore other paths

  • Graph representation: Each vertex maps to indices of sticks it belongs to

  • Path counting: We count the number of sticks used, not vertices

Conclusion

This solution uses DFS with backtracking to find the longest possible stick by exploring all valid combinations. The time complexity is exponential in the worst case, but efficient for small inputs typical in such problems.

Updated on: 2026-03-25T12:11:47+05:30

341 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements