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
Check if the given number K is enough to reach the end of an array in Python
We need to traverse an array and check if we can reach the end with a given number k. The rules are: decrement k by 1 for non-prime numbers, and refill k to its original value when encountering prime numbers. If k becomes 0 or negative and the next element is non-prime, we cannot proceed.
Problem Analysis
Let's trace through the example: nums = [8, 5, 6, 7, 8], k = 2
-
nums[0] = 8(not prime) ?k = 1 -
nums[1] = 5(prime) ?k = 2(refilled) -
nums[2] = 6(not prime) ?k = 1 -
nums[3] = 7(prime) ?k = 2(refilled) -
nums[4] = 8(not prime) ?k = 1
We successfully reach the end, so the answer is True.
Algorithm Steps
- Store the original value of
k - For each element in the array:
- If the element is prime, refill
kto its original value - If the element is not prime, decrement
kby 1 - If
k ? 0and we're not at the last element and the next element is not prime, returnFalse
True if we successfully traverse the entire arrayImplementation
def isPrime(num):
if num < 2:
return False
if num == 2:
return True
if num % 2 == 0:
return False
for i in range(3, int(num**0.5) + 1, 2):
if num % i == 0:
return False
return True
def canReachEnd(arr, k):
original_k = k
for i in range(len(arr)):
if isPrime(arr[i]):
k = original_k # Refill k to original value
else:
k -= 1 # Decrement k for non-prime
# Check if we can continue to next element
if k <= 0 and i < (len(arr) - 1) and not isPrime(arr[i + 1]):
return False
return True
# Test the function
nums = [8, 5, 6, 7, 8]
k = 2
result = canReachEnd(nums, k)
print(f"Can reach end: {result}")
# Test with another example
nums2 = [4, 6, 8, 10]
k2 = 1
result2 = canReachEnd(nums2, k2)
print(f"Can reach end: {result2}")
Can reach end: True Can reach end: False
How It Works
The algorithm maintains a counter k that represents our remaining "fuel". Prime numbers act as refueling stations that restore k to its original value, while non-prime numbers consume fuel. The key insight is that we fail only when we run out of fuel (k ? 0) and the next element is also non-prime, meaning we cannot refuel.
Optimized Prime Check
The isPrime() function is optimized to check divisibility only up to the square root of the number, and it skips even numbers after checking for 2. This reduces the time complexity from O(n) to O(?n) for prime checking.
Conclusion
This solution efficiently determines if we can traverse an array using prime numbers as refueling points. The algorithm runs in O(n?m) time where n is array length and m is the maximum array value.
