Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Fixed Point in Python
A fixed point in an array is an index where the element's value equals its position. Given a sorted array of unique integers, we need to find the smallest index i such that A[i] == i.
For example, in the array [-10, -5, 0, 3, 7], index 3 has value 3, making it a fixed point.
Algorithm
To solve this problem, we follow these steps ?
- Iterate through each index from 0 to length of array
- If
i == A[i], returnias the fixed point - If no fixed point is found, return
-1
Linear Search Approach
The straightforward approach checks each element sequentially ?
class Solution:
def fixedPoint(self, A):
for i in range(len(A)):
if i == A[i]:
return i
return -1
# Test the solution
solution = Solution()
result = solution.fixedPoint([-10, -5, 0, 3, 7])
print(f"Fixed point index: {result}")
Fixed point index: 3
Optimized Binary Search Approach
Since the array is sorted, we can use binary search for better efficiency ?
class Solution:
def fixedPointBinary(self, A):
left, right = 0, len(A) - 1
result = -1
while left <= right:
mid = (left + right) // 2
if A[mid] == mid:
result = mid
right = mid - 1 # Continue searching for smaller index
elif A[mid] < mid:
left = mid + 1
else:
right = mid - 1
return result
# Test both approaches
solution = Solution()
test_array = [-10, -5, 0, 3, 7]
linear_result = solution.fixedPoint(test_array)
binary_result = solution.fixedPointBinary(test_array)
print(f"Linear search result: {linear_result}")
print(f"Binary search result: {binary_result}")
Linear search result: 3 Binary search result: 3
Multiple Test Cases
Let's test with different arrays to understand the behavior ?
def test_fixed_point():
solution = Solution()
test_cases = [
[-10, -5, 0, 3, 7], # Fixed point at index 3
[0, 2, 5, 8, 17], # Fixed point at index 0
[-10, -5, 3, 4, 7, 9], # No fixed point
[1, 2, 3, 4, 5] # No fixed point
]
for i, arr in enumerate(test_cases):
result = solution.fixedPoint(arr)
print(f"Array {i+1}: {arr}")
print(f"Fixed point: {result}")
print()
test_fixed_point()
Array 1: [-10, -5, 0, 3, 7] Fixed point: 3 Array 2: [0, 2, 5, 8, 17] Fixed point: 0 Array 3: [-10, -5, 3, 4, 7, 9] Fixed point: -1 Array 4: [1, 2, 3, 4, 5] Fixed point: -1
Comparison
| Approach | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Linear Search | O(n) | O(1) | Simple implementation |
| Binary Search | O(log n) | O(1) | Large sorted arrays |
Conclusion
A fixed point occurs when A[i] == i. Use linear search for simplicity or binary search for optimal performance on large sorted arrays. The binary search approach leverages the sorted property to achieve O(log n) time complexity.
