LeetCode 335: Self Crossing Solution

Master LeetCode problem 335 (Self Crossing), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

335. Self Crossing

Problem Explanation

Explanation:

To solve this problem, we need to keep track of the boundary lines that the path can cross. We define four cases where a self-crossing can happen based on the distances moved. By checking these cases, we can determine if a self-crossing occurs.

  1. The current line crosses the line 3 steps ahead.
  2. The current line crosses the line 4 steps ahead.
  3. The current line crosses the line 5 steps ahead.
  4. The current line crosses the line 6 steps ahead.

We iterate through the array of distances, keeping track of the current location and the previous locations to determine if a self-crossing occurs.

  • Time complexity: O(n) where n is the length of the input array distance.
  • Space complexity: O(1)

Solution Code

class Solution {
    public boolean isSelfCrossing(int[] distance) {
        int n = distance.length;
        if (n < 4) return false;
        
        for (int i = 3; i < n; i++) {
            if (distance[i] >= distance[i - 2] && distance[i - 1] <= distance[i - 3]) return true;
            if (i >= 4 && distance[i - 1] == distance[i - 3] && distance[i] + distance[i - 4] >= distance[i - 2]) return true;
            if (i >= 5 && distance[i - 2] >= distance[i - 4] && distance[i] + distance[i - 4] >= distance[i - 2] && distance[i - 1] <= distance[i - 3] && distance[i - 1] + distance[i - 5] >= distance[i - 3]) return true;
        }
        return false;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 335 (Self Crossing)?

This page provides optimized solutions for LeetCode problem 335 (Self Crossing) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 335 (Self Crossing)?

The time complexity for LeetCode 335 (Self Crossing) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 335 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 335 in Java, C++, or Python.

Back to LeetCode Solutions