884375. Number of times graph cuts X-axis

Easy

Number of times graph cuts X-axis

Summary

Given a set of points (x, y) in a 2D plane, find out how many times the graph formed by these points cuts the x-axis. The graph is considered to cut the x-axis when a point's y-coordinate changes sign from negative to positive.

Detailed Explanation

The problem can be solved using a simple algorithm that iterates through the set of points and checks if the current point's y-coordinate has changed sign compared to the previous one. If it has, increment a counter to keep track of how many times the graph cuts the x-axis.

Here is a step-by-step breakdown of the solution:

  1. Initialize a variable cuts to 0, which will store the number of times the graph cuts the x-axis.
  2. Iterate through the set of points (x, y).
  3. For each point, check if the current point's y-coordinate has changed sign compared to the previous one. This can be done by checking if y * prev_y is negative or positive.
  4. If the sign has changed, increment the cuts variable.
  5. Update the prev_y variable with the current point's y-coordinate.

Time complexity: O(n), where n is the number of points in the set. Space complexity: O(1), as we only use a constant amount of space to store the cuts and prev_y variables.

Here is an ASCII art diagram illustrating the problem:

  +-----------------------+
  |       (0, -5)        |
  |     +---------------+  |
  |     |               |  |
  |     |  (-2, -3)    |  |
  |     |               |  |
  |     +---------------+  |
  |       (1, 2)        |
  |     +---------------+  |
  |     |               |  |
  |     |  (2, 4)      |  |
  |     |               |  |
  |     +---------------+  |
  +-----------------------+

Optimized Solutions

Java

View on GeeksforGeeks
public int countCuts(int[][] points) {
    int cuts = 0;
    double prev_y = Double.NEGATIVE_INFINITY;
    for (int[] point : points) {
        if ((point[1] * prev_y) < 0) {
            cuts++;
        }
        prev_y = point[1];
    }
    return cuts;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.