#335
Hard Algorithms Self crossing
Array Math Geometry
34.2% acceptance
Jan 12, 2026
416
522
You are given an array of integers distance.
You start at the point (0, 0) on an X-Y plane, and you move distance[0] meters to the north, then distance[1] meters to the west, distance[2] meters to the south, distance[3] meters to the east, and so on. In other words, after each move, your direction changes counter-clockwise.
Return true if your path crosses itself or false if it does not.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn is_self_crossing(distance: Vec<i32>) -> bool {
let n = distance.len();
if n < 4 {
return false;
}
for i in 3..n {
// Fourth line crosses first line
if distance[i] >= distance[i - 2] && distance[i - 1] <= distance[i - 3] {
return true;
}
// Fifth line crosses second line
if i >= 4 {
if distance[i - 1] == distance[i - 3]
&& distance[i] + distance[i - 4] >= distance[i - 2] {
return true;
}
}
// Sixth line crosses third line
if i >= 5 {
if distance[i - 2] >= distance[i - 4]
&& distance[i] + distance[i - 4] >= distance[i - 2]
&& distance[i - 1] + distance[i - 5] >= distance[i - 3]
&& distance[i - 1] <= distance[i - 3] {
return true;
}
}
}
false
}
}