- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 42 lines of Java from the credited upstream file 963.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 5 loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public double minAreaFreeRect(int[][] points) {3 long ans = Long.MAX_VALUE;4 5 Map<Integer, List<int[]>> centerToPoints = new HashMap<>();6 7 for (int[] A : points)8 for (int[] B : points) {9 int center = hash(A, B);10 if (centerToPoints.get(center) == null)11 centerToPoints.put(center, new ArrayList<>());12 centerToPoints.get(center).add(new int[] {A[0], A[1], B[0], B[1]});13 }14 15 16 for (List<int[]> pointPairs : centerToPoints.values())17 for (int[] ab : pointPairs)18 for (int[] cd : pointPairs) {19 final int ax = ab[0], ay = ab[1];20 final int cx = cd[0], cy = cd[1];21 final int dx = cd[2], dy = cd[3];22 23 24 if ((cx - ax) * (dx - ax) + (cy - ay) * (dy - ay) == 0) {25 final long squaredArea = dist(ax, ay, cx, cy) * dist(ax, ay, dx, dy);26 if (squaredArea > 0)27 ans = Math.min(ans, squaredArea);28 }29 }30 31 return ans == Long.MAX_VALUE ? 0 : Math.sqrt(ans);32 }33 34 private int hash(int[] p, int[] q) {35 return ((p[0] + q[0]) << 16) + (p[1] + q[1]);36 }37 38 private long dist(long px, long py, long qx, long qy) {39 return (px - qx) * (px - qx) + (py - qy) * (py - qy);40 }41}42