1393. Convex Turn Check
A landscaper marks the corners of a garden bed with pegs and strings a rope around them in order, returning to the first peg at the end. polygon[i] = [x, y] are the pegs, in the order the rope visits them, either clockwise or counter-clockwise. The rope never crosses itself, and the bed has positive area.
The bed is convex when the rope always turns the same way. Return true if that holds, otherwise false. Look at every triple of consecutive pegs, wrapping around at the end: the bed is not convex exactly when some triples turn left (positive cross product) and others turn right (negative). Triples of collinear pegs give a zero cross product and are ignored. Aim for O(n) time and O(1) extra space.
Example 1
- Input:
- polygon = [[0,0],[4,0],[4,4],[0,4]]
- Output:
- true
- Explanation:
All four turns are left turns, so the square is convex.
Example 2
- Input:
- polygon = [[0,0],[2,0],[2,1],[1,1],[1,2],[0,2]]
- Output:
- false
- Explanation:
The corner at (1, 1) turns the other way from the rest, so this L shape is not convex.
Example 3
- Input:
- polygon = [[0,0],[2,0],[4,0],[4,4],[0,4]]
- Output:
- true
- Explanation:
The peg at (2, 0) lies on a straight stretch and is ignored; every other turn is a left turn, so the shape is convex.
Constraints
3 ≤ n ≤ 1000; -104 ≤ x, y ≤ 104; the polygon is simple and has positive area.
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n)
- Space
- O(1)