[
sort
binary search
math
two pointers
]
BinarySearch 0314 Symmetric Blocks
Problem statement
https://binarysearch.com/problems/Symmetric-Blocks/
Solution
First of all array should be in non-increasing order.
We can look at all angles: elements, for which nums[i] != nums[i + 1]
. Then we check that all pairs are symmetric
Complexity
It is O(n)
for time and space.
Code
class Solution:
def solve(self, nums):
n = len(nums)
if any(x < y for x, y in zip(nums, nums[1:])): return False
cands = set()
for i, x, y in zip(range(1, n+1), nums, nums[1:] + [0]):
if x != y:
cands.add((i, x))
for a, b in cands:
if (b, a) not in cands: return False
return True
Remark
If we want O(n)
time and O(1)
space solution, we can use two poitners approach.