Minimum Gates to Connect All Regions

Farmer John starts at (0, 0) and walks on a farm following the string path.

Each character in path is one of:

  • 'N' → move north
  • 'S' → move south
  • 'E' → move east
  • 'W' → move west

Every time he moves, he builds a fence segment along that step. His path may revisit points, reuse fence segments, or cross older parts of the fence. As a result, the farm may get divided into multiple separated regions.

A gate can be added on any unit fence segment, allowing movement through that segment.

Return the minimum number of gates needed so that every region becomes reachable from every other region.

Example 1:

Input: path = "NESW"

Output: 1

Explanation:

The path makes one closed loop, creating one enclosed region.

So, 1 gate is enough.

Example 2:

Input: path = "NSNS"

Output: 0

Explanation:

This path only goes back and forth and does not form any closed region.

So, no gate is needed.

Now Your Turn!

Pick the correct output for the given input

Input: path = "NNEESSWW"

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= path.length <= 1000
  • path[i] is either 'N', 'S', 'E', or 'W'

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution {
public:
int minimumGates(string path) {
// Your code goes here
}
};
Test Case

Input:

Path