1392. Shoelace Twice Area
A surveyor records the corners of a fenced field as integer points, walking around its boundary once. polygon[i] = [x, y] is the i-th corner, consecutive corners are joined by straight fences, and the last corner connects back to the first. The walk may go clockwise or counter-clockwise, and some corners may lie on a straight stretch between their neighbours.
The fences never cross or touch each other except at shared corners, so the field is a simple polygon. Return twice the enclosed area, as a 64-bit integer; doubling keeps the value an integer for every lattice polygon. Coordinates can be negative and intermediate products reach 2 * 10^8, so sums need 64 bits. Aim for O(n) time and O(1) extra space.
Example 1
- Input:
- polygon = [[0,0],[1,0],[1,1],[0,1]]
- Output:
- 2
- Explanation:
The unit square has area 1, so twice the area is 2.
Example 2
- Input:
- polygon = [[0,0],[4,0],[0,3]]
- Output:
- 12
- Explanation:
The right triangle has area 6, so twice the area is 12.
Example 3
- Input:
- polygon = [[0,0],[0,3],[4,0]]
- Output:
- 12
- Explanation:
The same triangle walked clockwise still gives 12.
Constraints
3 ≤ n ≤ 1000; -104 ≤ x, y ≤ 104; the polygon is simple.
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)