inputs
stringlengths 50
14k
| targets
stringlengths 4
655k
|
|---|---|
Given an array of integers nums and an integer threshold, we will choose a positive integer divisor and divide all the array by it and sum the result of the division. Find the smallest divisor such that the result mentioned above is less than or equal to threshold.
Each result of division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5).
It is guaranteed that there will be an answer.
Example 1:
Input: nums = [1,2,5,9], threshold = 6
Output: 5
Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1.
If the divisor is 4 we can get a sum to 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2).
Example 2:
Input: nums = [2,3,5,7,11], threshold = 11
Output: 3
Example 3:
Input: nums = [19], threshold = 5
Output: 4
Constraints:
1 <= nums.length <= 5 * 10^4
1 <= nums[i] <= 10^6
nums.length <= threshold <= 10^6
|
import math
class Solution:
def smallestDivisor(self, nums: List[int], threshold: int) -> int:
self.nums = nums
self.threshold = threshold
num_sum = sum(nums)
l = math.floor(num_sum / threshold)-1
h = num_sum
m = math.ceil((l+h) / 2)
while h != m:
if self.validate_divisor(m):
h = m
else:
l = m
m = math.ceil((l+h) / 2)
return h
def validate_divisor(self, divisor):
if divisor <= 0:
return False
s = sum(math.ceil(x / divisor) for x in self.nums)
return s <= self.threshold
|
Given an array of integers nums and an integer threshold, we will choose a positive integer divisor and divide all the array by it and sum the result of the division. Find the smallest divisor such that the result mentioned above is less than or equal to threshold.
Each result of division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5).
It is guaranteed that there will be an answer.
Example 1:
Input: nums = [1,2,5,9], threshold = 6
Output: 5
Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1.
If the divisor is 4 we can get a sum to 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2).
Example 2:
Input: nums = [2,3,5,7,11], threshold = 11
Output: 3
Example 3:
Input: nums = [19], threshold = 5
Output: 4
Constraints:
1 <= nums.length <= 5 * 10^4
1 <= nums[i] <= 10^6
nums.length <= threshold <= 10^6
|
class Solution:
def smallestDivisor(self, nums: List[int], threshold: int) -> int:
def isThres(m):
tsum = 0
for n in nums:
tsum += n // m
if n % m > 0:
tsum += 1
if tsum <= threshold:
return True
l,r = 1, sum(nums)
while l < r:
m = l + r >> 1
if isThres(m):
r = m
else:
l = m + 1
return l
|
Given an array of integers nums and an integer threshold, we will choose a positive integer divisor and divide all the array by it and sum the result of the division. Find the smallest divisor such that the result mentioned above is less than or equal to threshold.
Each result of division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5).
It is guaranteed that there will be an answer.
Example 1:
Input: nums = [1,2,5,9], threshold = 6
Output: 5
Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1.
If the divisor is 4 we can get a sum to 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2).
Example 2:
Input: nums = [2,3,5,7,11], threshold = 11
Output: 3
Example 3:
Input: nums = [19], threshold = 5
Output: 4
Constraints:
1 <= nums.length <= 5 * 10^4
1 <= nums[i] <= 10^6
nums.length <= threshold <= 10^6
|
class Solution:
def smallestDivisor(self, nums: List[int], threshold: int) -> int:
# binary search
left = 1
right = max(nums)
while left <= right:
mid = left + (right - left) // 2
mid_left_result = self.divide_and_sum(mid - 1, nums)
mid_result = self.divide_and_sum(mid, nums)
if mid_left_result > threshold and mid_result <= threshold:
return mid
# move right
if mid_result > threshold:
left = mid + 1
# move left
if mid_left_result <= threshold:
right = mid - 1
def divide_and_sum(self, divisor, nums):
if divisor == 0:
return math.inf
result = 0
for num in nums:
result += ceil(num / divisor)
return result
|
Given an array of integers nums and an integer threshold, we will choose a positive integer divisor and divide all the array by it and sum the result of the division. Find the smallest divisor such that the result mentioned above is less than or equal to threshold.
Each result of division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5).
It is guaranteed that there will be an answer.
Example 1:
Input: nums = [1,2,5,9], threshold = 6
Output: 5
Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1.
If the divisor is 4 we can get a sum to 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2).
Example 2:
Input: nums = [2,3,5,7,11], threshold = 11
Output: 3
Example 3:
Input: nums = [19], threshold = 5
Output: 4
Constraints:
1 <= nums.length <= 5 * 10^4
1 <= nums[i] <= 10^6
nums.length <= threshold <= 10^6
|
import math
class Solution:
def smallestDivisor(self, nums: List[int], threshold: int) -> int:
# left, right = 1, max(nums)
# while left + 1 < right:
# mid = (left + right) // 2
# if self.get_sum(mid, nums) > threshold:
# left = mid
# else:
# right = mid
# if self.get_sum(left, nums) <= threshold:
# return left
# return right
# def get_sum(self, nmb, nums):
# if nmb == 0:
# return False
# val = 0
# for num in nums:
# val += math.ceil(num/nmb)
# return val
# def get_sum(self, divisor, nums):
# res = 0
# for n in nums:
# tmp = n // divisor
# if tmp * divisor < n:
# tmp += 1
# res += tmp
# return res
def chk(nmb):
if nmb == 0:
return False
val = 0
for num in nums:
val += math.ceil(num/nmb)
if val > threshold:
return False
return True
high = max(nums)
low = high//threshold
while low <= high:
mid = (low + high)//2
if chk(mid):
high = mid - 1
elif not chk(mid):
low = mid + 1
return low-1 if chk(low-1) else high+1
|
Given an array of integers nums and an integer threshold, we will choose a positive integer divisor and divide all the array by it and sum the result of the division. Find the smallest divisor such that the result mentioned above is less than or equal to threshold.
Each result of division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5).
It is guaranteed that there will be an answer.
Example 1:
Input: nums = [1,2,5,9], threshold = 6
Output: 5
Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1.
If the divisor is 4 we can get a sum to 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2).
Example 2:
Input: nums = [2,3,5,7,11], threshold = 11
Output: 3
Example 3:
Input: nums = [19], threshold = 5
Output: 4
Constraints:
1 <= nums.length <= 5 * 10^4
1 <= nums[i] <= 10^6
nums.length <= threshold <= 10^6
|
class Solution:
def smallestDivisor(self, nums: List[int], threshold: int) -> int:
def is_valid(select_num: int):
res = sum([math.ceil(num / select_num) for num in nums])
return None if res > threshold else res
if not nums: return 0
left, right = 1, 1000000000
while left < right:
middle = (left + right) // 2
if is_valid(middle):
right = middle
else:
left = middle + 1
return left if is_valid(left) else right
|
Given an array of integers nums and an integer threshold, we will choose a positive integer divisor and divide all the array by it and sum the result of the division. Find the smallest divisor such that the result mentioned above is less than or equal to threshold.
Each result of division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5).
It is guaranteed that there will be an answer.
Example 1:
Input: nums = [1,2,5,9], threshold = 6
Output: 5
Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1.
If the divisor is 4 we can get a sum to 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2).
Example 2:
Input: nums = [2,3,5,7,11], threshold = 11
Output: 3
Example 3:
Input: nums = [19], threshold = 5
Output: 4
Constraints:
1 <= nums.length <= 5 * 10^4
1 <= nums[i] <= 10^6
nums.length <= threshold <= 10^6
|
class Solution:
def find(self, nums, div):
ans = 0
for i in nums:
ans += i//div
if i%div!=0:
ans += 1
return ans
def smallestDivisor(self, nums: List[int], threshold: int) -> int:
low = 1
high = max(nums)
while low<high:
mid = (low+high)//2
cur = self.find(nums, mid)
if mid>1:
prev = self.find(nums, mid-1)
else:
prev = 0
if mid == 1 and cur<=threshold:
return 1
if cur<=threshold and prev>threshold:
return mid
elif cur>threshold:
low = mid+1
elif prev<=threshold:
high = mid-1
return (low+high)//2
|
Given an array of integers nums and an integer threshold, we will choose a positive integer divisor and divide all the array by it and sum the result of the division. Find the smallest divisor such that the result mentioned above is less than or equal to threshold.
Each result of division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5).
It is guaranteed that there will be an answer.
Example 1:
Input: nums = [1,2,5,9], threshold = 6
Output: 5
Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1.
If the divisor is 4 we can get a sum to 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2).
Example 2:
Input: nums = [2,3,5,7,11], threshold = 11
Output: 3
Example 3:
Input: nums = [19], threshold = 5
Output: 4
Constraints:
1 <= nums.length <= 5 * 10^4
1 <= nums[i] <= 10^6
nums.length <= threshold <= 10^6
|
class Solution:
def smallestDivisor(self, nums: List[int], threshold: int) -> int:
def feasible(val):
total = 0
for i in nums:
total += (i-1)//val + 1
return total <= threshold
left,right = 1, max(nums)
while left < right:
mid = left + (right-left)//2
if feasible(mid):
right = mid
else:
left = mid + 1
return left
|
Given an array of integers nums and an integer threshold, we will choose a positive integer divisor and divide all the array by it and sum the result of the division. Find the smallest divisor such that the result mentioned above is less than or equal to threshold.
Each result of division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5).
It is guaranteed that there will be an answer.
Example 1:
Input: nums = [1,2,5,9], threshold = 6
Output: 5
Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1.
If the divisor is 4 we can get a sum to 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2).
Example 2:
Input: nums = [2,3,5,7,11], threshold = 11
Output: 3
Example 3:
Input: nums = [19], threshold = 5
Output: 4
Constraints:
1 <= nums.length <= 5 * 10^4
1 <= nums[i] <= 10^6
nums.length <= threshold <= 10^6
|
class Solution:
def smallestDivisor(self, nums: List[int], threshold: int) -> int:
r = max(nums)
l = 1
def calc(div):
s = sum([ceil(num / div) for num in nums])
return s <= threshold
while l < r:
mid = (l + r) // 2
val = calc(mid)
# print (\"[%d, %d] => %d v %r\" %(l, r, mid, val))
if calc(mid):
r = mid
else:
l = mid + 1
return l
|
Given an array of integers nums and an integer threshold, we will choose a positive integer divisor and divide all the array by it and sum the result of the division. Find the smallest divisor such that the result mentioned above is less than or equal to threshold.
Each result of division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5).
It is guaranteed that there will be an answer.
Example 1:
Input: nums = [1,2,5,9], threshold = 6
Output: 5
Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1.
If the divisor is 4 we can get a sum to 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2).
Example 2:
Input: nums = [2,3,5,7,11], threshold = 11
Output: 3
Example 3:
Input: nums = [19], threshold = 5
Output: 4
Constraints:
1 <= nums.length <= 5 * 10^4
1 <= nums[i] <= 10^6
nums.length <= threshold <= 10^6
|
class Solution:
def smallestDivisor(self, nums: List[int], threshold: int) -> int:
s = sum(nums)
l = len(nums)
L = max((s + threshold - 1) // threshold, 1) - 1
# worst case: every num is just one more of multiple of answer
t_ = max(threshold - l, 1)
U = (s + t_ - 1) // t_
while L + 1 < U:
m = (L + U) // 2
if sum((x + m - 1) // m for x in nums) <= threshold:
U = m
else:
L = m
return U
|
Given an array of integers nums and an integer threshold, we will choose a positive integer divisor and divide all the array by it and sum the result of the division. Find the smallest divisor such that the result mentioned above is less than or equal to threshold.
Each result of division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5).
It is guaranteed that there will be an answer.
Example 1:
Input: nums = [1,2,5,9], threshold = 6
Output: 5
Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1.
If the divisor is 4 we can get a sum to 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2).
Example 2:
Input: nums = [2,3,5,7,11], threshold = 11
Output: 3
Example 3:
Input: nums = [19], threshold = 5
Output: 4
Constraints:
1 <= nums.length <= 5 * 10^4
1 <= nums[i] <= 10^6
nums.length <= threshold <= 10^6
|
class Solution:
def smallestDivisor(self, nums: List[int], threshold: int) -> int:
def feasible(target):
total = sum([math.ceil(num/target) for num in nums] )
return total <= threshold
low,high=1,sum(nums)
while low < high:
mid = low+(high-low)//2
if feasible(mid):
high = mid
else:
low = mid+1
return low
|
Given an array of integers nums and an integer threshold, we will choose a positive integer divisor and divide all the array by it and sum the result of the division. Find the smallest divisor such that the result mentioned above is less than or equal to threshold.
Each result of division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5).
It is guaranteed that there will be an answer.
Example 1:
Input: nums = [1,2,5,9], threshold = 6
Output: 5
Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1.
If the divisor is 4 we can get a sum to 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2).
Example 2:
Input: nums = [2,3,5,7,11], threshold = 11
Output: 3
Example 3:
Input: nums = [19], threshold = 5
Output: 4
Constraints:
1 <= nums.length <= 5 * 10^4
1 <= nums[i] <= 10^6
nums.length <= threshold <= 10^6
|
import math
class Solution:
def smallestDivisor(self, nums: List[int], threshold: int) -> int:
def isDiv(mid):
s=0
for i in nums:
s+=math.ceil(i/mid)
# print(\"Sum\",s,mid)
return s<=threshold
def binsearch():
low=1
high=sum(nums)
while low<high:
mid=low+(high-low)//2
if isDiv(mid):
high=mid
else:
low=mid+1
return low
return binsearch()
|
Given an array of integers nums and an integer threshold, we will choose a positive integer divisor and divide all the array by it and sum the result of the division. Find the smallest divisor such that the result mentioned above is less than or equal to threshold.
Each result of division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5).
It is guaranteed that there will be an answer.
Example 1:
Input: nums = [1,2,5,9], threshold = 6
Output: 5
Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1.
If the divisor is 4 we can get a sum to 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2).
Example 2:
Input: nums = [2,3,5,7,11], threshold = 11
Output: 3
Example 3:
Input: nums = [19], threshold = 5
Output: 4
Constraints:
1 <= nums.length <= 5 * 10^4
1 <= nums[i] <= 10^6
nums.length <= threshold <= 10^6
|
import math
class Solution:
def smallestDivisor(self, nums: List[int], threshold: int) -> int:
if not nums:
return sys.maxsize
left, right = 1, 2
while right < sys.maxsize and self.get_sum(nums, right) > threshold:
left, right = right, right * 2
while left + 1 < right:
mid = (left + right) // 2
if self.get_sum(nums, mid) <= threshold:
right = mid
else:
left = mid
if self.get_sum(nums, left) <= threshold:
return left
return right
def get_sum(self, nums: List[int], divisor: int) -> int:
result = 0
for num in nums:
result += math.ceil(num / divisor)
return int(result)
|
Given an array of integers nums and an integer threshold, we will choose a positive integer divisor and divide all the array by it and sum the result of the division. Find the smallest divisor such that the result mentioned above is less than or equal to threshold.
Each result of division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5).
It is guaranteed that there will be an answer.
Example 1:
Input: nums = [1,2,5,9], threshold = 6
Output: 5
Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1.
If the divisor is 4 we can get a sum to 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2).
Example 2:
Input: nums = [2,3,5,7,11], threshold = 11
Output: 3
Example 3:
Input: nums = [19], threshold = 5
Output: 4
Constraints:
1 <= nums.length <= 5 * 10^4
1 <= nums[i] <= 10^6
nums.length <= threshold <= 10^6
|
from math import ceil
def is_fine(nums,val,threshold):
tot = 0
for i in nums:
tot += ceil(i/val)
if tot <= threshold:
return True
else:
return False
def bSearch(l,r,nums,threshold):
if l <= r:
mid = (l+r)//2
high_val = is_fine(nums,mid,threshold)
low_val = is_fine(nums,mid-1,threshold)
if high_val is True and low_val is False:
return mid
elif high_val is False and low_val is False:
return bSearch(mid+1,r,nums,threshold)
else:
return bSearch(l,mid-1,nums,threshold)
else:
return None
class Solution:
def smallestDivisor(self, nums: List[int], threshold: int) -> int:
if sum(nums) <= threshold:
return 1
return bSearch(2,10**6,nums,threshold)
|
Given an array of integers nums and an integer threshold, we will choose a positive integer divisor and divide all the array by it and sum the result of the division. Find the smallest divisor such that the result mentioned above is less than or equal to threshold.
Each result of division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5).
It is guaranteed that there will be an answer.
Example 1:
Input: nums = [1,2,5,9], threshold = 6
Output: 5
Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1.
If the divisor is 4 we can get a sum to 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2).
Example 2:
Input: nums = [2,3,5,7,11], threshold = 11
Output: 3
Example 3:
Input: nums = [19], threshold = 5
Output: 4
Constraints:
1 <= nums.length <= 5 * 10^4
1 <= nums[i] <= 10^6
nums.length <= threshold <= 10^6
|
class Solution:
def smallestDivisor(self, nums: List[int], threshold: int) -> int:
def calc(nums, divisor):
s = 0
for num in nums:
if num % divisor == 0:
s += num // divisor
else:
s += num // divisor + 1
# print(divisor, s)
return s
left = 1
right = sum(nums) // (threshold-1) + threshold*100
print((left, right))
while left < right:
mid = (left+right) // 2
cur_res = calc(nums, mid)
if cur_res > threshold:
left = mid + 1
else:
right = mid
return left
|
Given an array of integers nums and an integer threshold, we will choose a positive integer divisor and divide all the array by it and sum the result of the division. Find the smallest divisor such that the result mentioned above is less than or equal to threshold.
Each result of division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5).
It is guaranteed that there will be an answer.
Example 1:
Input: nums = [1,2,5,9], threshold = 6
Output: 5
Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1.
If the divisor is 4 we can get a sum to 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2).
Example 2:
Input: nums = [2,3,5,7,11], threshold = 11
Output: 3
Example 3:
Input: nums = [19], threshold = 5
Output: 4
Constraints:
1 <= nums.length <= 5 * 10^4
1 <= nums[i] <= 10^6
nums.length <= threshold <= 10^6
|
class Solution:
def smallestDivisor(self, nums: List[int], threshold: int) -> int:
end = 1
start = end
def findSum(div):
return sum([math.ceil(n / div) for n in nums])
while True:
if findSum(end) > threshold:
start = end
end *= 2
else:
break
while end > start:
mid = (start + end) // 2
# print(start, end, mid, findSum(mid))
if findSum(mid) > threshold:
start = mid + 1
else:
end = mid
return end
|
A sequence of numbers is called a wiggle sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence.
For example, [1,7,4,9,2,5] is a wiggle sequence because the differences (6,-3,5,-7,3) are alternately positive and negative. In contrast, [1,4,7,2,5] and [1,7,4,5,5] are not wiggle sequences, the first because its first two differences are positive and the second because its last difference is zero.
Given a sequence of integers, return the length of the longest subsequence that is a wiggle sequence. A subsequence is obtained by deleting some number of elements (eventually, also zero) from the original sequence, leaving the remaining elements in their original order.
Examples:
Input: [1,7,4,9,2,5]
Output: 6
The entire sequence is a wiggle sequence.
Input: [1,17,5,10,13,15,10,5,16,8]
Output: 7
There are several subsequences that achieve this length. One is [1,17,10,13,10,16,8].
Input: [1,2,3,4,5,6,7,8,9]
Output: 2
Follow up:
Can you do it in O(n) time?
Credits:Special thanks to @agave and @StefanPochmann for adding this problem and creating all test cases.
|
class Solution:
def wiggleMaxLength(self, arr):
"""
:type nums: List[int]
:rtype: int
"""
n = len(arr)
if n < 2:
return n
wsl = [0]*n
wsl[0] = 1
for cur in range(1, n):
prev = cur - 1
if arr[cur] > arr[prev] and wsl[prev] <= 1:
wsl[cur] = abs(wsl[prev]) + 1
elif arr[cur] < arr[prev] and wsl[prev] > 0:
wsl[cur] = (abs(wsl[prev]) + 1)*(-1)
else:
wsl[cur] = wsl[prev]
return abs(wsl[n-1])
|
A sequence of numbers is called a wiggle sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence.
For example, [1,7,4,9,2,5] is a wiggle sequence because the differences (6,-3,5,-7,3) are alternately positive and negative. In contrast, [1,4,7,2,5] and [1,7,4,5,5] are not wiggle sequences, the first because its first two differences are positive and the second because its last difference is zero.
Given a sequence of integers, return the length of the longest subsequence that is a wiggle sequence. A subsequence is obtained by deleting some number of elements (eventually, also zero) from the original sequence, leaving the remaining elements in their original order.
Examples:
Input: [1,7,4,9,2,5]
Output: 6
The entire sequence is a wiggle sequence.
Input: [1,17,5,10,13,15,10,5,16,8]
Output: 7
There are several subsequences that achieve this length. One is [1,17,10,13,10,16,8].
Input: [1,2,3,4,5,6,7,8,9]
Output: 2
Follow up:
Can you do it in O(n) time?
Credits:Special thanks to @agave and @StefanPochmann for adding this problem and creating all test cases.
|
class Solution:
def wiggleMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
if n < 2: return n
prev_diff = nums[1] - nums[0]
count = 2 if prev_diff != 0 else 1
for i in range(2, n):
diff = nums[i] - nums[i-1]
if (diff > 0 and prev_diff <= 0) or (diff < 0 and prev_diff >= 0):
count += 1
prev_diff = diff
return count
|
A sequence of numbers is called a wiggle sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence.
For example, [1,7,4,9,2,5] is a wiggle sequence because the differences (6,-3,5,-7,3) are alternately positive and negative. In contrast, [1,4,7,2,5] and [1,7,4,5,5] are not wiggle sequences, the first because its first two differences are positive and the second because its last difference is zero.
Given a sequence of integers, return the length of the longest subsequence that is a wiggle sequence. A subsequence is obtained by deleting some number of elements (eventually, also zero) from the original sequence, leaving the remaining elements in their original order.
Examples:
Input: [1,7,4,9,2,5]
Output: 6
The entire sequence is a wiggle sequence.
Input: [1,17,5,10,13,15,10,5,16,8]
Output: 7
There are several subsequences that achieve this length. One is [1,17,10,13,10,16,8].
Input: [1,2,3,4,5,6,7,8,9]
Output: 2
Follow up:
Can you do it in O(n) time?
Credits:Special thanks to @agave and @StefanPochmann for adding this problem and creating all test cases.
|
class Solution:
def wiggleMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) < 2:
return len(nums)
diffs = []
for i in range(1, len(nums)):
diffs.append(nums[i] - nums[i-1])
prev_idx = 0
while diffs[prev_idx] == 0:
prev_idx += 1
if prev_idx == len(diffs):
return 1 # all equal
cnt = 2
for i in range(prev_idx + 1, len(diffs)):
if diffs[prev_idx] * diffs[i] < 0:
cnt += 1
prev_idx = i
return cnt
|
A sequence of numbers is called a wiggle sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence.
For example, [1,7,4,9,2,5] is a wiggle sequence because the differences (6,-3,5,-7,3) are alternately positive and negative. In contrast, [1,4,7,2,5] and [1,7,4,5,5] are not wiggle sequences, the first because its first two differences are positive and the second because its last difference is zero.
Given a sequence of integers, return the length of the longest subsequence that is a wiggle sequence. A subsequence is obtained by deleting some number of elements (eventually, also zero) from the original sequence, leaving the remaining elements in their original order.
Examples:
Input: [1,7,4,9,2,5]
Output: 6
The entire sequence is a wiggle sequence.
Input: [1,17,5,10,13,15,10,5,16,8]
Output: 7
There are several subsequences that achieve this length. One is [1,17,10,13,10,16,8].
Input: [1,2,3,4,5,6,7,8,9]
Output: 2
Follow up:
Can you do it in O(n) time?
Credits:Special thanks to @agave and @StefanPochmann for adding this problem and creating all test cases.
|
class Solution:
def wiggleMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 0:
return 0
max_up = [1]
max_down = [1]
for i in range(1, len(nums)):
if nums[i] > nums[i-1]:
max_up.append(max_down[i-1]+1)
max_down.append(max_down[i-1])
elif nums[i] < nums[i-1]:
max_up.append(max_up[i-1])
max_down.append(max_up[i-1]+1)
else:
max_up.append(max_up[i-1])
max_down.append(max_down[i-1])
return max(max_up[-1], max_down[-1])
|
A sequence of numbers is called a wiggle sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence.
For example, [1,7,4,9,2,5] is a wiggle sequence because the differences (6,-3,5,-7,3) are alternately positive and negative. In contrast, [1,4,7,2,5] and [1,7,4,5,5] are not wiggle sequences, the first because its first two differences are positive and the second because its last difference is zero.
Given a sequence of integers, return the length of the longest subsequence that is a wiggle sequence. A subsequence is obtained by deleting some number of elements (eventually, also zero) from the original sequence, leaving the remaining elements in their original order.
Examples:
Input: [1,7,4,9,2,5]
Output: 6
The entire sequence is a wiggle sequence.
Input: [1,17,5,10,13,15,10,5,16,8]
Output: 7
There are several subsequences that achieve this length. One is [1,17,10,13,10,16,8].
Input: [1,2,3,4,5,6,7,8,9]
Output: 2
Follow up:
Can you do it in O(n) time?
Credits:Special thanks to @agave and @StefanPochmann for adding this problem and creating all test cases.
|
class Solution:
def wiggleMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
l = len(nums)
dp = [0] * l
up = [0] * l
down = [0] * l
up[0] = down[0] = 1
for i in range(1, l):
if nums[i - 1] < nums[i]:
up[i] = up[i - 1]
down[i] = up[i - 1] + 1
elif nums[i - 1] > nums[i]:
down[i] = down[i - 1]
up[i] = down[i - 1] + 1
else:
up[i] = up[i - 1]
down[i] = down[i - 1]
return max(down[-1], up[-1])
|
A sequence of numbers is called a wiggle sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence.
For example, [1,7,4,9,2,5] is a wiggle sequence because the differences (6,-3,5,-7,3) are alternately positive and negative. In contrast, [1,4,7,2,5] and [1,7,4,5,5] are not wiggle sequences, the first because its first two differences are positive and the second because its last difference is zero.
Given a sequence of integers, return the length of the longest subsequence that is a wiggle sequence. A subsequence is obtained by deleting some number of elements (eventually, also zero) from the original sequence, leaving the remaining elements in their original order.
Examples:
Input: [1,7,4,9,2,5]
Output: 6
The entire sequence is a wiggle sequence.
Input: [1,17,5,10,13,15,10,5,16,8]
Output: 7
There are several subsequences that achieve this length. One is [1,17,10,13,10,16,8].
Input: [1,2,3,4,5,6,7,8,9]
Output: 2
Follow up:
Can you do it in O(n) time?
Credits:Special thanks to @agave and @StefanPochmann for adding this problem and creating all test cases.
|
class Solution:
def wiggleMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 0:
return 0
if len(nums) == 1:
return 1
N = len(nums)
sol = [0 for _ in nums]
sol[0] = [1,1] #starting with -, starting with +
for i in range(1,N):
new = [0,0]
if nums[i] > nums[i-1]:
new[0] = sol[i-1][1]+1
else:
new[0] = sol[i-1][0]
if nums[i] < nums[i-1]:
new[1] = sol[i-1][0]+1
else:
new[1] = sol[i-1][1]
sol[i] = new
return max(sol[-1])
|
A sequence of numbers is called a wiggle sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence.
For example, [1,7,4,9,2,5] is a wiggle sequence because the differences (6,-3,5,-7,3) are alternately positive and negative. In contrast, [1,4,7,2,5] and [1,7,4,5,5] are not wiggle sequences, the first because its first two differences are positive and the second because its last difference is zero.
Given a sequence of integers, return the length of the longest subsequence that is a wiggle sequence. A subsequence is obtained by deleting some number of elements (eventually, also zero) from the original sequence, leaving the remaining elements in their original order.
Examples:
Input: [1,7,4,9,2,5]
Output: 6
The entire sequence is a wiggle sequence.
Input: [1,17,5,10,13,15,10,5,16,8]
Output: 7
There are several subsequences that achieve this length. One is [1,17,10,13,10,16,8].
Input: [1,2,3,4,5,6,7,8,9]
Output: 2
Follow up:
Can you do it in O(n) time?
Credits:Special thanks to @agave and @StefanPochmann for adding this problem and creating all test cases.
|
class Solution:
def wiggleMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
if n == 0:
return 0
gn = [1] * n
trend = 0
for i in range(1, n):
prev = nums[i-1]
if prev == nums[i]:
gn[i] = gn[i-1]
else:
if trend == 0:
gn[i] = gn[i-1] + 1
trend = 1 if nums[i] > prev else -1
continue
if (nums[i] > prev and trend == -1) or (nums[i] < prev and trend == 1):
gn[i] = gn[i-1] + 1
trend = -trend
else:
gn[i] = gn[i-1]
return gn[-1]
|
A sequence of numbers is called a wiggle sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence.
For example, [1,7,4,9,2,5] is a wiggle sequence because the differences (6,-3,5,-7,3) are alternately positive and negative. In contrast, [1,4,7,2,5] and [1,7,4,5,5] are not wiggle sequences, the first because its first two differences are positive and the second because its last difference is zero.
Given a sequence of integers, return the length of the longest subsequence that is a wiggle sequence. A subsequence is obtained by deleting some number of elements (eventually, also zero) from the original sequence, leaving the remaining elements in their original order.
Examples:
Input: [1,7,4,9,2,5]
Output: 6
The entire sequence is a wiggle sequence.
Input: [1,17,5,10,13,15,10,5,16,8]
Output: 7
There are several subsequences that achieve this length. One is [1,17,10,13,10,16,8].
Input: [1,2,3,4,5,6,7,8,9]
Output: 2
Follow up:
Can you do it in O(n) time?
Credits:Special thanks to @agave and @StefanPochmann for adding this problem and creating all test cases.
|
class Solution:
def wiggleMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
l = len(nums)
if l == 0:
return 0
elif l == 1:
return 1
st = 1
while nums[0] == nums[st]:
st += 1
if st == l:
return 1
one, two = (nums[0], nums[st])
cnt = 2
for i in range(st+1, l):
if nums[i] == two:
continue
if one < two:
if nums[i] > two:
two = nums[i]
else:
one = two
two = nums[i]
cnt += 1
else:
if nums[i] < two:
two = nums[i]
else:
one = two
two = nums[i]
cnt += 1
return cnt
|
A sequence of numbers is called a wiggle sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence.
For example, [1,7,4,9,2,5] is a wiggle sequence because the differences (6,-3,5,-7,3) are alternately positive and negative. In contrast, [1,4,7,2,5] and [1,7,4,5,5] are not wiggle sequences, the first because its first two differences are positive and the second because its last difference is zero.
Given a sequence of integers, return the length of the longest subsequence that is a wiggle sequence. A subsequence is obtained by deleting some number of elements (eventually, also zero) from the original sequence, leaving the remaining elements in their original order.
Examples:
Input: [1,7,4,9,2,5]
Output: 6
The entire sequence is a wiggle sequence.
Input: [1,17,5,10,13,15,10,5,16,8]
Output: 7
There are several subsequences that achieve this length. One is [1,17,10,13,10,16,8].
Input: [1,2,3,4,5,6,7,8,9]
Output: 2
Follow up:
Can you do it in O(n) time?
Credits:Special thanks to @agave and @StefanPochmann for adding this problem and creating all test cases.
|
class Solution:
def wiggleMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if nums==[]:
return 0
if len(nums)<2:
return 1
max_length=1
state=0
i=1
while i<len(nums):
while state==0 and i<len(nums):
if nums[i-1]>nums[i]:
max_length=max_length+1
state=2
if nums[i-1]<nums[i]:
max_length=max_length+1
state=1
i=i+1
while state==1 and i<len(nums):
if nums[i-1]>nums[i]:
max_length=max_length+1
state=2
i=i+1
while state==2 and i<len(nums):
if nums[i-1]<nums[i]:
state=1
max_length=max_length+1
i=i+1
return max_length
|
A sequence of numbers is called a wiggle sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence.
For example, [1,7,4,9,2,5] is a wiggle sequence because the differences (6,-3,5,-7,3) are alternately positive and negative. In contrast, [1,4,7,2,5] and [1,7,4,5,5] are not wiggle sequences, the first because its first two differences are positive and the second because its last difference is zero.
Given a sequence of integers, return the length of the longest subsequence that is a wiggle sequence. A subsequence is obtained by deleting some number of elements (eventually, also zero) from the original sequence, leaving the remaining elements in their original order.
Examples:
Input: [1,7,4,9,2,5]
Output: 6
The entire sequence is a wiggle sequence.
Input: [1,17,5,10,13,15,10,5,16,8]
Output: 7
There are several subsequences that achieve this length. One is [1,17,10,13,10,16,8].
Input: [1,2,3,4,5,6,7,8,9]
Output: 2
Follow up:
Can you do it in O(n) time?
Credits:Special thanks to @agave and @StefanPochmann for adding this problem and creating all test cases.
|
class Solution:
def wiggleMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
l = len(nums)
if l == 0:
return 0
elif l == 1:
return 1
st = 1
while nums[0] == nums[st]:
st += 1
if st == l:
return 1
seq = [nums[0], nums[st]]
for i in range(st+1, l):
if nums[i] == seq[-1]:
continue
if seq[-1] < seq[-2]:
if nums[i] < seq[-1]:
seq[-1] = nums[i]
else:
seq.append(nums[i])
else:
if nums[i]>seq[-1]:
seq[-1] = nums[i]
else:
seq.append(nums[i])
return len(seq)
|
A sequence of numbers is called a wiggle sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence.
For example, [1,7,4,9,2,5] is a wiggle sequence because the differences (6,-3,5,-7,3) are alternately positive and negative. In contrast, [1,4,7,2,5] and [1,7,4,5,5] are not wiggle sequences, the first because its first two differences are positive and the second because its last difference is zero.
Given a sequence of integers, return the length of the longest subsequence that is a wiggle sequence. A subsequence is obtained by deleting some number of elements (eventually, also zero) from the original sequence, leaving the remaining elements in their original order.
Examples:
Input: [1,7,4,9,2,5]
Output: 6
The entire sequence is a wiggle sequence.
Input: [1,17,5,10,13,15,10,5,16,8]
Output: 7
There are several subsequences that achieve this length. One is [1,17,10,13,10,16,8].
Input: [1,2,3,4,5,6,7,8,9]
Output: 2
Follow up:
Can you do it in O(n) time?
Credits:Special thanks to @agave and @StefanPochmann for adding this problem and creating all test cases.
|
class Solution:
def wiggleMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums = [nums[i] for i in range(len(nums)) if i == 0 or nums[i] != nums[i-1]]
print(nums)
total = min(2,len(nums))
for i in range(1,len(nums)-1):
if nums[i] > nums[i-1] and nums[i] > nums[i+1]:
total += 1
elif nums[i] < nums[i-1] and nums[i] < nums[i+1]:
total += 1
return total
|
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Example 1:
Input: [3,2,1,5,6,4] and k = 2
Output: 5
Example 2:
Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
|
class Solution:
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
nums = sorted(nums, reverse=True)
return nums[k - 1]
|
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Example 1:
Input: [3,2,1,5,6,4] and k = 2
Output: 5
Example 2:
Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
|
class Solution:
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
nums.sort()
return nums[len(nums) - k]
|
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Example 1:
Input: [3,2,1,5,6,4] and k = 2
Output: 5
Example 2:
Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
|
class Solution:
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
heap = []
for num in nums:
heapq.heappush(heap,num)
for _ in range(len(nums)-k):
heapq.heappop(heap)
return heapq.heappop(heap)
|
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Example 1:
Input: [3,2,1,5,6,4] and k = 2
Output: 5
Example 2:
Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
|
class Solution:
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
if not nums: return -1;
pq = [];
for num in nums:
if len(pq) < k:
heapq.heappush(pq,num);
else:
popped = heapq.heappop(pq);
if popped < num:
heapq.heappush(pq, num);
else:
heapq.heappush(pq, popped);
return heapq.heappop(pq);
|
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Example 1:
Input: [3,2,1,5,6,4] and k = 2
Output: 5
Example 2:
Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
|
class Solution:
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
def partition(nums, ind, i, j):
big, scan = i, i
nums[ind], nums[j] = nums[j], nums[ind]
while scan < j:
if nums[scan] > nums[j]:
nums[big], nums[scan] = nums[scan], nums[big]
big += 1
scan += 1
nums[j], nums[big] = nums[big], nums[j]
# print(nums)
# print(big)
return big
# 12 53 - 1 09
i, j = 0, len(nums)-1
while i <= j:
ind = random.randint(i, j)
new_ind = partition(nums, ind, i, j)
if new_ind == k-1:
return nums[new_ind]
elif new_ind < k-1:
i = new_ind + 1
else:
j = new_ind - 1
return -1
|
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Example 1:
Input: [3,2,1,5,6,4] and k = 2
Output: 5
Example 2:
Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
|
class Solution:
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
sor = sorted(nums)
lenn = len(nums)
return sor[lenn-1-(k-1)]
|
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Example 1:
Input: [3,2,1,5,6,4] and k = 2
Output: 5
Example 2:
Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
|
class Solution:
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
return sorted(nums)[len(nums) - k]
|
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Example 1:
Input: [3,2,1,5,6,4] and k = 2
Output: 5
Example 2:
Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
|
class Solution:
def swap(self, A, i, j ):
if A[i] != A[j]:
A[i],A[j] = A[j],A[i]
def partition(self, A, p, r):
self.swap(A, r, random.randint(p, r))
x = A[r]
j = p - 1
for i in range(p, r):
if A[i] <= x:
j += 1
self.swap(A, i, j)
j += 1
self.swap(A, r, j)
return j
def findElement(self, A, k):
low, high = 0, len(A) - 1
while low < high:
i = self.partition(A, low, high)
if i > k:
high = i - 1
elif i < k :
low = i + 1
else:
return A[k]
return A[k]
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
return self.findElement(nums, len(nums) - k)
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
longest_word = max([len(word) for word in words])
if len(result) != longest_word and len(result) != longest_word + 1:
return False
result_indices = []
acc = 0
all_chars = []
front_indices = []
for i in range(1, longest_word + 1):
for word in words:
if i == len(word):
front_indices.append(acc)
if i <= len(word):
all_chars.append(word[i * -1])
acc += 1
if i == len(result):
front_indices.append(acc)
result_indices.append(acc)
acc += 1
all_chars.append(result[i * -1])
if len(result) > longest_word:
result_indices.append(acc)
front_indices.append(acc)
all_chars.append(result[0])
self.words = words
self.result = result
self.result_indices = result_indices
self.all_chars = all_chars
self.mappings = {}
self.used_chars = set()
self.front_indices = front_indices
return self.backtrack(0, 0)
def backtrack(self, current_i: int, carry: int) -> bool:
if current_i == len(self.all_chars):
if self.mappings[self.result[0]] == 0:
return False
return True
cur_char = self.all_chars[current_i]
if current_i in self.result_indices:
code, new_carry = self.verify(self.result_indices.index(current_i), carry)
if code == 0:
return False
else:
if self.backtrack(current_i + 1, new_carry):
return True
if code == 2:
self.used_chars.remove(self.mappings[cur_char])
del self.mappings[cur_char]
return False
if cur_char in self.mappings:
if current_i in self.front_indices and self.mappings[cur_char] == 0:
return False
return self.backtrack(current_i + 1, carry)
for i in range(10):
if current_i in self.front_indices and i == 0:
continue
if i not in self.used_chars:
self.mappings[cur_char] = i
self.used_chars.add(i)
if self.backtrack(current_i + 1, carry):
return True
del self.mappings[cur_char]
self.used_chars.remove(i)
return False
def verify(self, index: int, carry: int) -> (int, int):
cur_sum = carry
for word in self.words:
if index < len(word):
cur_sum += self.mappings[word[index * -1 -1]]
carry = int(cur_sum / 10)
cur_sum = cur_sum % 10
result_char = self.result[index * -1 - 1]
if result_char in self.mappings:
if self.mappings[result_char] != cur_sum:
return 0, 0
else:
return 1, carry
else:
if cur_sum in self.used_chars:
return 0, 0
self.mappings[result_char] = cur_sum
self.used_chars.add(cur_sum)
return 2, carry
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
max_len = len(result)
if max(len(w) for w in words) > max_len:
return False
level = [[word[-i-1] for word in words if i<len(word)] for i in range(max_len)]
level_set = [set([result[-i-1]] + level[i]) for i in range(max_len)]
used_digits = set()
nonzero_chars = set(word[0] for word in words + [result])
assignments = {}
def isSAT(eqn_index, carry):
if eqn_index >= max_len:
return carry == 0
remaining_terms = []
for t in level_set[eqn_index]:
if t not in assignments:
for guess in range(t in nonzero_chars, 10):
if guess in used_digits:
continue
assignments[t] = guess
used_digits.add(guess)
if isSAT(eqn_index, carry):
return True
del assignments[t]
used_digits.remove(guess)
return False
s = sum(assignments[c] for c in level[eqn_index]) + carry
if s % 10 != assignments[result[-eqn_index-1]]:
return False
return isSAT(eqn_index +1, s // 10)
return isSAT(0, 0)
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
words.append(result)
M, N = len(words), max(list(map(len, words)))
dic = {}
rem = [None] * 10
lead = set([w[0] for w in words])
def backtrack(i, j, cur):
if j == N:
return cur == 0
if i == M:
return not cur % 10 and backtrack(0, j + 1, cur // 10)
if j >= len(words[i]):
return backtrack(i + 1, j, cur)
t = words[i][~j]
sign = 1 if i < M - 1 else -1
if t in dic:
return backtrack(i + 1, j, cur + dic[t] * sign)
else:
for k, r in enumerate(rem):
if not r and (k or t not in lead):
dic[t] = k
rem[k] = t
if backtrack(i + 1, j, cur + dic[t] * sign):
return True
del dic[t]
rem[k] = None
return False
return backtrack(0, 0, 0)
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
max_len = len(result)
if max(len(w) for w in words) > max_len:
return False
level = [[word[-i-1] for word in words if i<len(word)] for i in range(max_len)]
level_set = [set([result[-i-1]] + level[i]) for i in range(max_len)]
used_digits = set()
nonzero_chars = set(word[0] for word in words + [result])
assignments = {}
def isSAT(eqn_index, carry):
if eqn_index >= max_len:
return carry == 0
for t in level_set[eqn_index]:
if t not in assignments:
for guess in range(t in nonzero_chars, 10):
if guess in used_digits:
continue
assignments[t] = guess
used_digits.add(guess)
if isSAT(eqn_index, carry):
return True
del assignments[t]
used_digits.remove(guess)
return False
s = sum(assignments[c] for c in level[eqn_index]) + carry
if s % 10 != assignments[result[-eqn_index-1]]:
return False
return isSAT(eqn_index +1, s // 10)
return isSAT(0, 0)
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
if max([len(w) for w in words]) > len(result):
return False
lead_letters = set([w[0] for w in words + [result]])
letters = []
for k in range(1, len(result) + 1):
for w in words:
if len(w) >= k and w[-k] not in [x[0] for x in letters]:
letters.append((w[-k], k))
letters.append((result[-k], -k))
# print(letters)
letter2num = {}
num2letter = ['']*10
nums = '0123456789'
def helper(k):
if k == len(letters):
return True
letter, digit = letters[k][0], letters[k][1]
if digit < 0:
left = sum([int(''.join([letter2num[ch] for ch in w[digit:]])) for w in words])
if left < 10 ** (-digit-1):
return False
num = int(str(left)[digit])
if letter not in letter2num and not num2letter[num]:
letter2num[letter] = str(num)
num2letter[num] = letter
if helper(k + 1):
return True
letter2num.pop(letter)
num2letter[int(num)] = ''
elif num2letter[num] != letter or (letter in letter2num and letter2num[letter] != str(num)):
return False
else:
return helper(k + 1)
else:
if letter not in letter2num:
num_range = nums if letter not in lead_letters else nums[1:]
for num in num_range:
if not num2letter[int(num)]:
letter2num[letter] = num
num2letter[int(num)] = letter
if helper(k+1):
return True
letter2num.pop(letter)
num2letter[int(num)] = ''
return False
else:
return helper(k + 1)
return helper(0)
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
n = len(result)
if max(len(w) for w in words) > n:
return False
level = [[w[-k - 1] for w in words if k < len(w)] for k in range(n)]
level_set = [set(level[k]) | {result[-k - 1]} for k in range(n)]
leading = set(w[0] for w in words) | {result[0]}
val = {k: None for k in set.union(set(result), *(set(w) for w in words))}
used = set()
def search(k, carry):
if k == n:
return carry == 0
for c in level_set[k]:
if val[c] is None:
for v in range(c in leading, 10):
if v not in used:
val[c] = v
used.add(v)
if search(k, carry):
return True
val[c] = None
used.remove(v)
return False
s = sum(val[c] for c in level[k]) + carry
if s % 10 != val[result[-k - 1]]:
return False
return search(k + 1, s // 10)
return search(0, 0)
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
max_len = len(result)
if max(len(w) for w in words) > max_len:
return False
use_count = Counter(''.join(words +[result]))
level = [[word[-i-1] for word in words if i<len(word)] for i in range(max_len)]
level_set = [set([result[-i-1]] + level[i]) for i in range(max_len)]
used_digits = set()
nonzero_chars = set(word[0] for word in words + [result])
assignments = {}
def isSAT(eqn_index, carry):
if eqn_index >= max_len:
return carry == 0
remaining_terms = [t for t in level_set[eqn_index] if t not in assignments]
if remaining_terms:
term_to_guess = max(remaining_terms, key=lambda x:use_count[x])
for guess in range(term_to_guess in nonzero_chars, 10):
if guess in used_digits:
continue
assignments[term_to_guess] = guess
used_digits.add(guess)
if isSAT(eqn_index, carry):
return True
del assignments[term_to_guess]
used_digits.remove(guess)
return False
s = sum(assignments[c] for c in level[eqn_index]) + carry
if s % 10 != assignments[result[-eqn_index-1]]:
return False
return isSAT(eqn_index +1, s // 10)
return isSAT(0, 0)
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
self.words = words
self.result = result
self.front_chars = set([word[0] for word in words] + [result[0]])
self.result_indices = []
self.all_chars = []
new_words = words + [result]
while len(new_words) > 0:
for i in range(len(new_words)):
self.all_chars.append(new_words[i][-1])
new_words[i] = new_words[i][:-1]
self.result_indices.append(len(self.all_chars) - 1)
new_words = [word for word in new_words if len(word) > 0]
self.mappings = {}
self.used_chars = set()
return self.backtrack(0, 0)
def backtrack(self, current_i: int, carry: int) -> bool:
if current_i == len(self.all_chars):
return True
cur_char = self.all_chars[current_i]
if current_i in self.result_indices:
code, new_carry = self.verify(self.result_indices.index(current_i), carry)
if code == 0:
return False
else:
if self.backtrack(current_i + 1, new_carry):
return True
if code == 2:
self.used_chars.remove(self.mappings[cur_char])
del self.mappings[cur_char]
return False
if cur_char in self.mappings:
return self.backtrack(current_i + 1, carry)
for i in range(10):
if cur_char in self.front_chars and i == 0:
continue
if i not in self.used_chars:
self.mappings[cur_char] = i
self.used_chars.add(i)
if self.backtrack(current_i + 1, carry):
return True
del self.mappings[cur_char]
self.used_chars.remove(i)
return False
def verify(self, index: int, carry: int) -> (int, int):
cur_sum = carry
for word in self.words:
if index < len(word):
cur_sum += self.mappings[word[index * -1 -1]]
carry = int(cur_sum / 10)
cur_sum = cur_sum % 10
result_char = self.result[index * -1 - 1]
if result_char in self.mappings:
if self.mappings[result_char] != cur_sum:
return 0, 0
else:
return 1, carry
else:
if cur_sum in self.used_chars:
return 0, 0
if result_char in self.front_chars and cur_sum == 0:
return 0, 0
self.mappings[result_char] = cur_sum
self.used_chars.add(cur_sum)
return 2, carry
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
def backtrack(ch_pos_to_end, num_choices, iter_idx, lhs, rhs):
if ch_pos_to_end > len(result):
return True
mul = pow(10, ch_pos_to_end - 1)
if iter_idx < len(words):
word = words[iter_idx]
idx = len(word) - ch_pos_to_end
if idx >= 0:
if word[idx] not in num_mappings:
for n in num_choices:
if n == 0 and word[idx] == word[0]:
continue
num_mappings[word[idx]] = n
if backtrack(ch_pos_to_end, num_choices - {n}, iter_idx + 1,
lhs + num_mappings[word[idx]] * mul,
rhs):
return True
del num_mappings[word[idx]]
else:
return backtrack(ch_pos_to_end, num_choices, iter_idx + 1, lhs + num_mappings[word[idx]] * mul, rhs)
else:
return backtrack(ch_pos_to_end, num_choices, iter_idx + 1, lhs, rhs)
elif iter_idx == len(words):
idx = len(result) - ch_pos_to_end
if result[idx] not in num_mappings:
for n in num_choices:
if n == 0 and result[idx] == result[0]:
continue
new_rhs = rhs + n * mul
if not str(lhs).endswith(str(new_rhs)):
continue
num_mappings[result[idx]] = n
if backtrack(ch_pos_to_end + 1, num_choices - {n}, 0, lhs, new_rhs):
return True
del num_mappings[result[idx]]
else:
added = num_mappings[result[idx]]
if not str(lhs).endswith(str(rhs + added * mul)):
return False
return backtrack(ch_pos_to_end + 1, num_choices, 0, lhs, rhs + added * mul)
return False
max_len_words = max([len(w) for w in words])
if max_len_words > len(result):
return False
num_mappings = {}
nums = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}
return backtrack(1, nums, 0, 0, 0)
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
class Solution(object):
def isSolvable(self, words, result):
words.append(result)
R, C = len(words), max(map(len, words))
assigned = {}
assigned_inv = [None] * 10
def search(column, row, bal):
if column >= C:
return bal == 0
if row == R:
return bal % 10 == 0 and search(column + 1, 0, bal // 10)
word = words[row]
if column >= len(word):
return search(column, row + 1, bal)
letter = word[~column]
sign = 1 if row < R - 1 else -1
if letter in assigned:
if (assigned[letter] or len(word) == 1 or column != len(word) - 1):
return search(column, row + 1, bal + sign * assigned[letter])
return False
else:
for d, ad in enumerate(assigned_inv):
if ad is None and (d or len(word) == 1 or column != len(word) - 1):
assigned_inv[d] = letter
assigned[letter] = d
if search(column, row + 1, bal + sign * d):
return True
assigned_inv[d] = None
del assigned[letter]
return False
return search(0, 0, 0)
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
# backtracking?
# awice ++
words.append(result)
R, C = len(words), max(list(map(len, words)))
used = {}
used_d = [None] * 10
def backtrack(row, col, bal):
if col >= C:
return bal == 0 and all(used[w[0]] != 0 for w in words)
if row == R:
return bal % 10 == 0 and backtrack(0, col + 1, bal // 10)
word = words[row]
if col >= len(word):
return backtrack(row + 1, col, bal)
letter = word[-1 - col]
sign = 1 if row < R - 1 else -1
if letter in used:
return backtrack(row + 1, col, bal + sign * used[letter])
else:
for d, ad in enumerate(used_d):
if ad is None and (d or col != len(word) - 1):
# start backtracking
used[letter] = d
used_d[d] = letter
if backtrack(row + 1, col, bal + sign * d):
return True
# restore to previous state
used_d[d] = None
del used[letter]
return False
return backtrack(0, 0, 0)
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
max_len = len(result)
if max(len(w) for w in words) > max_len:
return False
equations = [[result[-i-1]] + [word[-i-1] for word in words if i<len(word)] for i in range(max_len)]
used_digits = set()
nonzero_chars = set(word[0] for word in words + [result])
assignments = {}
print(equations)
def isSAT(eqn_index, carry):
if eqn_index >= max_len:
return carry == 0
remaining_terms = []
for t in equations[eqn_index]:
if t not in assignments:
for guess in range(t in nonzero_chars, 10):
if guess in used_digits:
continue
assignments[t] = guess
used_digits.add(guess)
if isSAT(eqn_index, carry):
return True
del assignments[t]
used_digits.remove(guess)
return False
s = sum(assignments[c] for c in equations[eqn_index][1:]) + carry
if s % 10 != assignments[equations[eqn_index][0]]:
return False
return isSAT(eqn_index +1, s // 10)
return isSAT(0, 0)
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
max_len = len(result)
if max(len(w) for w in words) > max_len:
return False
equations = [[result[-i-1]] + [word[-i-1] for word in words if i<len(word)] for i in range(max_len)]
used_digits = set()
nonzero_chars = set(word[0] for word in words + [result])
assignments = {}
def isSAT(eqn_index, carry):
if eqn_index >= max_len:
return carry == 0
remaining_terms = []
for t in equations[eqn_index]:
if t not in assignments:
for guess in range(t in nonzero_chars, 10):
if guess in used_digits:
continue
assignments[t] = guess
used_digits.add(guess)
if isSAT(eqn_index, carry):
return True
del assignments[t]
used_digits.remove(guess)
return False
s = sum(assignments[c] for c in equations[eqn_index][1:]) + carry
if s % 10 != assignments[equations[eqn_index][0]]:
return False
return isSAT(eqn_index +1, s // 10)
return isSAT(0, 0)
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
words.append(result)
assigned = {}
assigned_inv = [None] * 10
self.r,self.c=len(words),max(list(map(len, words)))
def dfs(column,row,bal):
if column>=self.c:
return bal==0 and all(assigned[i[0]]!=0 for i in words)
if row==self.r:
return bal%10==0 and dfs(column+1,0,bal//10)
word=words[row]
if column>=len(word):
return dfs(column,row+1,bal)
letter=word[~column]
sign= 1 if row<self.r-1 else -1
if letter in assigned:
return dfs(column,row+1,bal+sign*assigned[letter])
else:
for num,c in enumerate(assigned_inv):
if c is None and (num or column!=len(word)-1):
assigned[letter]=num
assigned_inv[num]=letter
if dfs(column,row+1,bal+sign*num):
return True
assigned_inv[num]=None
del assigned[letter]
return False
return dfs(0,0,0)
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
words.append(result)
assigned = {}
assigned_inv = [None] * 10
self.r,self.c=len(words),max(list(map(len, words)))
def dfs(column,row,bal):
if column==self.c:
return bal==0 and all(assigned[i[0]]!=0 for i in words)
if row==self.r:
return bal%10==0 and dfs(column+1,0,bal//10)
word=words[row]
if column>=len(word):
return dfs(column,row+1,bal)
letter=word[~column]
sign= 1 if row<self.r-1 else -1
if letter in assigned:
return dfs(column,row+1,bal+sign*assigned[letter])
else:
for num,c in enumerate(assigned_inv):
if c is None and (num or column!=len(word)-1):
assigned[letter]=num
assigned_inv[num]=letter
if dfs(column,row+1,bal+sign*num):
return True
assigned_inv[num]=None
del assigned[letter]
return False
return dfs(0,0,0)
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
def solve(i, j, carry):
# The current column assignment is over, so check for validity
if j == len(words):
csum = carry
for k in range(len(words)):
csum += 0 if i >= len(words[k]) else assign[words[k][i]]
# We have come to column i, but the result itself is not long enough.
if i >= len(result): return False
if result[i] in assign:
return csum % 10 == assign[result[i]] and solve(i+1, 0, csum // 10) # i th char of result is already assigned, so check if its valid and go to next column i+1 and start from word 0
else:
# If the current digit can't be assigned to ith char of result or if its 0 and we are looking at first char of a word: then return False
if (csum % 10) in assign.values() or (csum % 10 == 0 and i == len(result) - 1):
return False
assign[result[i]] = csum % 10
ret = solve(i+1, 0, csum // 10)
del assign[result[i]]
return ret
if i == len(result):
return i >= max(len(w) for w in words) and carry == 0 and all(assign[w[len(w)-1]] != 0 for w in words + [result])
# Handle length of word less than the column we are looking at OR the ith column char of the jth word is already assigned previously
if i >= len(words[j]) or words[j][i] in assign: return solve(i, j+1, carry)
for val in range(10):
if val == 0 and i == len(words[j]) - 1: continue # Handle not to assign 0 for first letter of a word
if val not in assign.values():
assign[words[j][i]] = val
ret = solve(i, j+1, carry)
if ret: return True
del assign[words[j][i]]
return False
result = result[::-1]
words = [w[::-1] for w in words]
assign = dict()
return solve(0, 0, 0)
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
n = len(words)
mapper = {}
maxlen = 0
for w in words:
maxlen = max(maxlen, len(w))
for c in w:
mapper[c] = -1
if len(result) < maxlen or len(result) - maxlen > 1:
return False
for c in result:
mapper[c] = -1
used = [0] * 10
def solve(i, j, s):
if j == n:
l = len(result) - i
if l < 0:
if s != 0:
return False
for w in words:
if mapper[w[0]] == 0:
return False
if mapper[result[0]] == 0:
return False
return True
c, s = divmod(s, 10)
if mapper[result[l]] >= 0:
if mapper[result[l]] == s:
return solve(i + 1, 0, c)
return False
if used[s]:
return False
mapper[result[l]] = s
used[s] = 1
res = solve(i + 1, 0, c)
mapper[result[l]] = -1
used[s] = 0
return res
w = words[j]
l = len(w) - i
if l < 0:
return solve(i, j + 1, s)
if mapper[w[l]] >= 0:
return solve(i, j + 1, s + mapper[w[l]])
for k in range(10):
if used[k]:
continue
used[k] = 1
mapper[w[l]] = k
if solve(i, j + 1, s + k):
return True
used[k] = 0
mapper[w[l]] = -1
return False
return solve(1, 0, 0)
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
max_len = len(result)
if max(len(w) for w in words) > max_len:
return False
words = [word.rjust(max_len, '#') for word in words]
result = result.rjust(max_len, '#')
equations = list(zip(result, *words))
used_digits = set()
nonzero_chars = set(equations[0])
assignments = {'#':0}
def isSAT(eqn_index, carry):
if eqn_index<0:
return carry == 0
remaining_terms = []
for t in equations[eqn_index]:
if t not in assignments:
for guess in range(t in nonzero_chars, 10):
if guess in used_digits:
continue
assignments[t] = guess
used_digits.add(guess)
if isSAT(eqn_index, carry):
return True
del assignments[t]
used_digits.remove(guess)
return False
s = sum(assignments[c] for c in equations[eqn_index][1:]) + carry
if s % 10 != assignments[equations[eqn_index][0]]:
return False
else:
return isSAT(eqn_index - 1, s // 10)
return isSAT(max_len-1, 0)
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
max_len = len(result)
if max(len(w) for w in words) > max_len:
return False
words = [word.rjust(max_len, '#') for word in words]
result = result.rjust(max_len, '#')
equations = list(zip(result, *words))
used_digits = set()
nonzero_chars = set(equations[0])
assignments = {'#':0}
def isSAT(eqn_index, carry):
if eqn_index<0:
return carry == 0
remaining_terms = []
for t in equations[eqn_index]:
if t not in assignments:
for guess in range(10):
if guess in used_digits:
continue
if guess == 0 and t in nonzero_chars:
continue
assignments[t] = guess
used_digits.add(guess)
if isSAT(eqn_index, carry):
return True
del assignments[t]
used_digits.remove(guess)
return False
s = sum(assignments[c] for c in equations[eqn_index][1:]) + carry
if s % 10 != assignments[equations[eqn_index][0]]:
return False
else:
return isSAT(eqn_index - 1, s // 10)
return isSAT(max_len-1, 0)
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
allwords = words + [result]
n = max(list(map(len, allwords)))
firstc = set(word[0] for word in allwords)
if len(result) < n : return False
def dfs(charidx, wordidx, carry, visited, char2digit):
if charidx == n: return carry == 0
if wordidx == len(allwords):
tot = sum(char2digit[word[~charidx]] if charidx < len(word) else 0 for word in words) + carry
if (tot % 10) == char2digit[result[~charidx]]:
return dfs(charidx + 1, 0, tot // 10, visited, char2digit)
else:
return False
if wordidx < len(words) and charidx >= len(words[wordidx]):
return dfs(charidx, wordidx+1, carry, visited, char2digit)
c = allwords[wordidx][~charidx]
first = 1 if c in firstc else 0
if c in char2digit:
return dfs(charidx, wordidx+1, carry, visited, char2digit)
else:
for d in range(first, 10):
if d not in visited:
visited.add(d)
char2digit[c] = d
if dfs(charidx, wordidx+1, carry, visited, char2digit): return True
del char2digit[c]
visited.remove(d)
return False
return dfs(0, 0, 0, set(), {})
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
from itertools import permutations, zip_longest
from collections import OrderedDict
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
self.matched_chars = list(zip_longest(*[result[::-1]]+[w[::-1] for w in words]))
self.first_chars = set([result[0]]+[w[0] for w in words])
self.chars = []
self.free_vars = []
self.idx = {}
observed = set()
for chars in self.matched_chars:
free_vars = []
for c in chars:
if c is None:
continue
if c not in observed:
self.chars.append(c)
free_vars.append(c)
observed.add(c)
self.idx[c]=len(self.idx)
self.free_vars.append(free_vars)
#print(self.free_vars)
#print(self.chars)
return self.dfs(0,(),0)
def dfs(self, i, used_digits, carry):
#pemutations
if i >= len(self.matched_chars):
#print('R:',used_digits)
return not max(used_digits[self.idx[f]]==0 for f in self.first_chars)
free_vars = self.free_vars[i]
perms = permutations(set(range(10))-set(list(used_digits)),len(free_vars))
for p in perms:
values = tuple(list(used_digits)+list(p))
#check for contradiction
nxt_carry = self.contradict(values,i,carry)
if nxt_carry<0:
continue
if self.dfs(i+1,values,nxt_carry):
return True
return False
def contradict(self, values, i, carry):
r, *i = self.matched_chars[i]
s = sum(values[self.idx[d]] for d in i if d)+carry
if (s-values[self.idx[r]])%10:
return -1
return s//10
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
allWords = words + [result]
firstChars = set(word[0] for word in allWords if len(word) > 1)
n = max(list(map(len, allWords)))
if len(result) < n: return False
def dfs(charIdx, wordIdx, carry, visited, char2digit):
if charIdx == n: return carry == 0
if wordIdx == len(allWords):
# time to check the final status for the current digit
sums = sum(char2digit[word[~charIdx]] if charIdx < len(word) else 0 for word in words) + carry
if sums % 10 == char2digit[result[-charIdx - 1]]:
return dfs(charIdx + 1, 0, sums // 10, visited, char2digit)
else:
return False # prune. To support this, using -charIdx - 1 to visit from right/low to left/high
# current word length is too short to check, move to check next word
if wordIdx < len(words) and charIdx >= len(words[wordIdx]):
return dfs(charIdx, wordIdx + 1, carry, visited, char2digit)
c = allWords[wordIdx][-charIdx-1]
if c in char2digit:
# if current word's current char already map to a digit, continue with next word
return dfs(charIdx, wordIdx + 1, carry, visited, char2digit)
else:
# otherwise try all possibilities via dfs
firstDigit = 1 if c in firstChars else 0
for digit in range(firstDigit, 10):
if digit not in visited:
visited.add(digit)
char2digit[c] = digit
if dfs(charIdx, wordIdx + 1, carry, visited, char2digit): return True
del char2digit[c]
visited.remove(digit) # restore visited and char2digit by discarding the copy
return False
return dfs(0, 0, 0, set(), {})
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
n = len(words)
mapper = {}
maxlen = 0
for w in words:
maxlen = max(maxlen, len(w))
for c in w:
mapper[c] = -1
if len(result) < maxlen or len(result) - maxlen > 1:
return False
for c in result:
mapper[c] = -1
used = [0] * 10
def solve(i, j, s):
if j == n:
l = len(result) - i
if l < 0:
if s != 0:
return False
if any([mapper[w[0]] == 0 for w in words]):
return False
if mapper[result[0]] == 0:
return False
return True
c, s = divmod(s, 10)
if mapper[result[l]] >= 0:
if mapper[result[l]] == s:
return solve(i + 1, 0, c)
return False
if used[s]:
return False
mapper[result[l]] = s
used[s] = 1
res = solve(i + 1, 0, c)
mapper[result[l]] = -1
used[s] = 0
return res
w = words[j]
l = len(w) - i
if l < 0:
return solve(i, j + 1, s)
if mapper[w[l]] >= 0:
return solve(i, j + 1, s + mapper[w[l]])
for k in range(10):
if used[k]:
continue
used[k] = 1
mapper[w[l]] = k
if solve(i, j + 1, s + k):
return True
used[k] = 0
mapper[w[l]] = -1
return False
return solve(1, 0, 0)
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
allwords = words + [result]
n = max(list(map(len, allwords)))
firstc = set(word[0] for word in allwords)
if len(result) < n : return False
def dfs(charidx, wordidx, carry, visited, char2digit):
if charidx == n: return carry == 0
if wordidx == len(allwords):
tot = sum(char2digit[word[~charidx]] if charidx < len(word) else 0 for word in words) + carry
if (tot % 10) == char2digit[result[~charidx]]:
return dfs(charidx + 1, 0, tot // 10, visited, char2digit)
return False
if wordidx < len(words) and charidx >= len(words[wordidx]):
return dfs(charidx, wordidx+1, carry, visited, char2digit)
c = allwords[wordidx][~charidx]
first = 1 if c in firstc else 0
if c in char2digit:
return dfs(charidx, wordidx+1, carry, visited, char2digit)
for d in range(first, 10):
if d not in visited:
visited.add(d)
char2digit[c] = d
if dfs(charidx, wordidx+1, carry, visited, char2digit): return True
del char2digit[c]
visited.remove(d)
return False
return dfs(0, 0, 0, set(), {})
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
from itertools import permutations, zip_longest
from collections import OrderedDict
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
self.matched_chars = list(zip_longest(*[result[::-1]]+[w[::-1] for w in words]))
self.first_chars = set([result[0]]+[w[0] for w in words])
self.chars = []
self.free_vars = []
self.idx = {}
observed = set()
for chars in self.matched_chars:
free_vars = []
for c in chars:
if c is None:
continue
if c not in observed:
self.chars.append(c)
free_vars.append(c)
observed.add(c)
self.idx[c]=len(self.idx)
self.free_vars.append(free_vars)
#print(self.free_vars)
#print(self.chars)
return self.dfs(0,(),0)
#@lru_cache(maxsize=None)
def dfs(self, i, used_digits, carry):
#pemutations
if i >= len(self.matched_chars):
#print('R:',used_digits)
return not max(used_digits[self.idx[f]]==0 for f in self.first_chars)
free_vars = self.free_vars[i]
perms = permutations(set(range(10))-set(list(used_digits)),len(free_vars))
for p in perms:
values = tuple(list(used_digits)+list(p))
#check for contradiction
nxt_carry = self.contradict(values,i,carry)
if nxt_carry<0:
continue
if self.dfs(i+1,values,nxt_carry):
return True
return False
def contradict(self, values, i, carry):
r, *i = self.matched_chars[i]
s = sum(values[self.idx[d]] for d in i if d)+carry
if (s-values[self.idx[r]])%10:
return -1
return s//10
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
# 1307. Verbal Arithmetic Puzzle
# version 2
def make_zip (lists):
i = 0
maxlength = max (len (l) for l in lists)
ans = []
while i < maxlength:
ans.append ([l[i] for l in lists if i < len (l)])
i += 1
return ans
def make_order (words, result):
order = []
formulas = {}
for i in range (len (result)):
for ch in [*(words[i]), result[i]]:
if ch not in order:
order.append (ch)
order.append (f'c{i+1}')
lhs = words[i]
rhs = result[i]
if i > 0:
lhs.append (f'c{i}')
excess = f'c{i+1}'
formulas[excess] = (lhs, rhs, excess)
# order determined
return order, formulas
def find_free (repl, ch, nonzero):
start = 1 if ch in nonzero else 0
choices = set (range (start, 10))
for x, y in repl.items ():
if y in choices: choices.remove (y)
yield from choices
def find_value (n, repl, crepl):
return repl[n] if n in repl else crepl[n]
def find_excess (lhs, rhs, repl, crepl):
return sum (find_value (x, repl, crepl) for x in lhs) - find_value (rhs, repl, crepl)
def walk_solutions (puzzle, index, repl, crepl):
(words, result, order, formulas, nonzero) = puzzle
if index == len (order):
# check top digit zero
last_ch = order[-1]
if crepl[last_ch] != 0:
return
yield repl
else:
ch = order[index]
if len (ch) == 1:
for digit in find_free (repl, ch, nonzero):
repl[ch] = digit
yield from walk_solutions (puzzle, index + 1, repl, crepl)
del repl[ch]
else:
formula = formulas[ch]
(lhs, rhs, _) = formula
excess = find_excess (lhs, rhs, repl, crepl)
if excess >= 0 and excess % 10 == 0:
# successful
crepl[ch] = excess // 10
yield from walk_solutions (puzzle, index + 1, repl, crepl)
del crepl[ch]
def is_solvable (words, result):
n = len (words)
maxword = 10 ** max (len (w) for w in words) - 1
minresult = 10 ** (len (result) - 1)
if n * maxword < minresult:
return False
if not all (len (w) <= len (result) for w in words):
return False
nonzero = {m[0] for m in [*words, result] if len (m) > 1}
result = [ch for ch in result[::-1]]
words = make_zip ([w[::-1] for w in words])
while len (words) < len (result):
words.append ([])
order, formulas = make_order (words, result)
puzzle = (words, result, order, formulas, nonzero)
return any (walk_solutions (puzzle, 0, {}, {}))
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
return is_solvable(words, result)
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
from itertools import permutations, zip_longest
from collections import OrderedDict
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
self.matched_chars = list(zip_longest(*[result[::-1]]+[w[::-1] for w in words]))
self.first_chars = set([result[0]]+[w[0] for w in words])
self.chars = []
self.free_vars = []
self.idx = {}
observed = set()
for chars in self.matched_chars:
free_vars = []
for c in chars:
if c is None:
continue
if c not in observed:
self.chars.append(c)
free_vars.append(c)
observed.add(c)
self.idx[c]=len(self.idx)
self.free_vars.append(free_vars)
#print(self.free_vars)
#print(self.chars)
return self.dfs(0,(),0)
@lru_cache(maxsize=None)
def dfs(self, i, used_digits, carry):
#pemutations
if i >= len(self.matched_chars):
#print('R:',used_digits)
return not max(used_digits[self.idx[f]]==0 for f in self.first_chars)
free_vars = self.free_vars[i]
perms = permutations(set(range(10))-set(list(used_digits)),len(free_vars))
for p in perms:
values = tuple(list(used_digits)+list(p))
#check for contradiction
nxt_carry = self.contradict(values,i,carry)
if nxt_carry<0:
continue
if self.dfs(i+1,values,nxt_carry):
return True
return False
def contradict(self, values, i, carry):
r, *i = self.matched_chars[i]
s = sum(values[self.idx[d]] for d in i if d)+carry
if (s-values[self.idx[r]])%10:
return -1
return s//10
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
allWords = words + [result]
firstChars = set(word[0] for word in allWords if len(word) > 1)
n = max(list(map(len, allWords)))
if len(result) < n: return False
def dfs(charIdx, wordIdx, carry, visited, char2digit):
if charIdx == n: return carry == 0
if wordIdx == len(allWords):
# time to check the final status for the current digit
sums = sum(char2digit[word[~charIdx]] if charIdx < len(word) else 0 for word in words) + carry
if sums % 10 == char2digit[result[-charIdx - 1]]:
return dfs(charIdx + 1, 0, sums // 10, visited, char2digit)
else:
return False # prune. To support this, using -charIdx - 1 to visit from right/low to left/high
# current word length is too short to check, move to check next word
if wordIdx < len(words) and charIdx >= len(words[wordIdx]):
return dfs(charIdx, wordIdx + 1, carry, visited, char2digit)
c = allWords[wordIdx][-charIdx-1]
if c in char2digit:
# if current word's current char already map to a digit, continue with next word
return dfs(charIdx, wordIdx + 1, carry, visited, char2digit)
else:
# otherwise try all possibilities via dfs
firstDigit = 1 if c in firstChars else 0
for digit in range(firstDigit, 10):
if digit not in visited:
visited.add(digit)
char2digit[c] = digit
if dfs(charIdx, wordIdx + 1, carry, visited, char2digit.copy()): return True
visited.remove(digit) # restore visited and char2digit by discarding the copy
return False
return dfs(0, 0, 0, set(), {})
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
from itertools import permutations, zip_longest
from collections import OrderedDict
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
self.matched_chars = list(zip_longest(*[result[::-1]]+[w[::-1] for w in words]))
self.first_chars = set([result[0]]+[w[0] for w in words])
self.chars = []
self.free_vars = []
self.idx = {}
observed = set()
for chars in self.matched_chars:
free_vars = []
for c in chars:
if c is None:
continue
if c not in observed:
self.chars.append(c)
free_vars.append(c)
observed.add(c)
self.idx[c]=len(self.idx)
self.free_vars.append(free_vars)
print((self.free_vars))
print((self.chars))
return self.dfs(0,(),0)
@lru_cache(maxsize=None)
def dfs(self, i, used_digits, carry):
#pemutations
if i >= len(self.matched_chars):
print(('R:',used_digits))
return not max(used_digits[self.idx[f]]==0 for f in self.first_chars)
free_vars = self.free_vars[i]
perms = permutations(set(range(10))-set(list(used_digits)),len(free_vars))
for p in perms:
values = tuple(list(used_digits)+list(p))
#check for contradiction
nxt_carry = self.contradict(values,i,carry)
if nxt_carry<0:
continue
if self.dfs(i+1,values,nxt_carry):
return True
return False
def contradict(self, values, i, carry):
r, *i = self.matched_chars[i]
s = sum(values[self.idx[d]] for d in i if d)+carry
if (s-values[self.idx[r]])%10:
return -1
return s//10
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
allWords = words + [result]
firstChars = set(word[0] for word in allWords if len(word) > 1)
n = max(list(map(len, allWords)))
if len(result) < n: return False
def dfs(charIdx, wordIdx, carry, visited, char2digit):
if charIdx == n: return carry == 0
if wordIdx == len(allWords):
# time to check the final status for the current digit
sums = sum(char2digit[word[-charIdx - 1]] if charIdx < len(word) else 0 for word in words) + carry
if sums % 10 == char2digit[result[-charIdx - 1]]:
return dfs(charIdx + 1, 0, sums // 10, visited, char2digit)
else:
return False # prune. To support this, using -charIdx - 1 to visit from right/low to left/high
# current word length is too short to check, move to check next word
if wordIdx < len(words) and charIdx >= len(words[wordIdx]):
return dfs(charIdx, wordIdx + 1, carry, visited, char2digit)
c = allWords[wordIdx][-charIdx-1]
if c in char2digit:
# if current word's current char already map to a digit, continue with next word
return dfs(charIdx, wordIdx + 1, carry, visited, char2digit)
else:
# otherwise try all possibilities via dfs
firstDigit = 1 if c in firstChars else 0
for digit in range(firstDigit, 10):
if digit not in visited:
visited.add(digit)
char2digit[c] = digit
if dfs(charIdx, wordIdx + 1, carry, visited, char2digit.copy()): return True
visited.remove(digit) # restore visited and char2digit by discarding the copy
return False
return dfs(0, 0, 0, set(), {})
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
n = len(words)
mapper = {}
maxlen = 0
for w in words:
maxlen = max(maxlen, len(w))
for c in w:
mapper[c] = -1
if len(result) < maxlen or len(result) - maxlen > 1:
return False
for c in result:
mapper[c] = -1
used = [0] * 10
def solve(i, j, s):
if j == n:
l = len(result) - i
if l < 0:
if s != 0:
return False
if any(mapper[w[0]] == 0 for w in words):
return False
if mapper[result[0]] == 0:
return False
return True
c, s = divmod(s, 10)
if mapper[result[l]] >= 0:
if mapper[result[l]] == s:
return solve(i + 1, 0, c)
return False
if used[s]:
return False
mapper[result[l]] = s
used[s] = 1
res = solve(i + 1, 0, c)
mapper[result[l]] = -1
used[s] = 0
return res
w = words[j]
l = len(w) - i
if l < 0:
return solve(i, j + 1, s)
if mapper[w[l]] >= 0:
return solve(i, j + 1, s + mapper[w[l]])
for k in range(10):
if used[k]:
continue
used[k] = 1
mapper[w[l]] = k
if solve(i, j + 1, s + k):
return True
used[k] = 0
mapper[w[l]] = -1
return False
return solve(1, 0, 0)
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
allwords = words + [result]
n = max(list(map(len, allwords)))
firstc = set(word[0] for word in allwords)
def dfs(charidx, wordidx, carry, visited, char2digit):
if charidx == n: return carry == 0
if wordidx == len(allwords):
tot = sum(char2digit[word[~charidx]] if charidx < len(word) else 0 for word in words) + carry
if tot % 10 == char2digit[result[~charidx]]:
return dfs(charidx+1, 0, tot//10, visited, char2digit)
return False
if wordidx < len(words) and charidx >= len(words[wordidx]):
return dfs(charidx, wordidx+1, carry, visited, char2digit)
c = allwords[wordidx][~charidx]
if c in char2digit:
return dfs(charidx, wordidx+1, carry, visited, char2digit)
first = 1 if c in firstc else 0
for d in range(first, 10):
if d not in visited:
visited.add(d)
char2digit[c] = d
if dfs(charidx, wordidx+1, carry, visited, char2digit): return True
del char2digit[c]
visited.remove(d)
return False
return dfs(0, 0, 0, set(), {})
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
allWords = words + [result]
firstChars = set(word[0] for word in allWords if len(word) > 1)
n = max(map(len, allWords))
if len(result) < n:
return False
def dfs(charIdx, wordIdx, carry, visited, char2digit):
if charIdx == n:
return carry == 0
if wordIdx == len(allWords):
# time to check the final status for the current digit
sums = sum(char2digit[word[-charIdx - 1]] if charIdx < len(word) else 0 for word in words) + carry
if sums % 10 == char2digit[result[-charIdx - 1]]:
return dfs(charIdx + 1, 0, sums // 10, visited, char2digit)
else:
return False # prune. To support this, using -charIdx - 1 to visit from right/low to left/high
# current word length is too short to check, move to check next word
if wordIdx < len(words) and charIdx >= len(words[wordIdx]):
return dfs(charIdx, wordIdx + 1, carry, visited, char2digit)
# 从后向前枚举,这样可以方便检测进而早点剪枝
c = allWords[wordIdx][-charIdx-1]
if c in char2digit:
# if current word's current char already map to a digit, continue with next word
return dfs(charIdx, wordIdx + 1, carry, visited, char2digit)
else:
# otherwise try all possibilities via dfs
firstDigit = 1 if c in firstChars else 0
for digit in range(firstDigit, 10):
if digit not in visited:
visited.add(digit)
char2digit[c] = digit
if dfs(charIdx, wordIdx + 1, carry, visited, char2digit.copy()):
return True
visited.remove(digit) # restore visited and char2digit by discarding the copy
return False
return dfs(0, 0, 0, set(), {})
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
start = set()
for word in words + [result]:
if len(word) > 1:
start.add(word[0])
n = max(list(map(len, words + [result])))
if len(result) < n:
return False
def dfs(idx, i, carry, visited, mp):
if idx == n:
return carry == 0
if i == len(words) + 1:
sums = sum(mp[word[-idx - 1]] if idx < len(word) else 0 for word in words) + carry
if sums % 10 == mp[result[-idx - 1]]:
carry = sums // 10
return dfs(idx + 1, 0, carry, visited, mp)
return False
if (i < len(words) and idx >= len(words[i])):
return dfs(idx, i + 1, carry, visited, mp)
tmp = words + [result]
ch = tmp[i][-idx-1]
if ch in mp:
return dfs(idx, i + 1, carry, visited, mp)
begin = 0
if ch in start:
begin = 1
for x in range(begin, 10):
if x not in visited:
visited.add(x)
mp[ch] = x
if dfs(idx, i + 1, carry, visited, mp.copy()):
return True
visited.remove(x)
return False
return dfs(0, 0, 0, set(), {})
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
allwords = words + [result]
n = max(list(map(len, allwords)))
firstc = set(word[0] for word in allwords)
def dfs(charidx, wordidx, carry, visited, char2digit):
if charidx == n: return carry == 0
if wordidx == len(allwords):
tot = sum(char2digit[word[~charidx]] if charidx < len(word) else 0 for word in words) + carry
if tot % 10 == char2digit[result[~charidx]]:
return dfs(charidx+1, 0, tot//10, visited, char2digit)
return False
if wordidx < len(words) and charidx >= len(words[wordidx]):
return dfs(charidx, wordidx+1, carry, visited, char2digit)
c = allwords[wordidx][~charidx]
first = 1 if c in firstc else 0
if c in char2digit:
return dfs(charidx, wordidx+1, carry, visited, char2digit)
for d in range(first, 10):
if d not in visited:
visited.add(d)
char2digit[c] = d
if dfs(charidx, wordidx+1, carry, visited, char2digit): return True
del char2digit[c]
visited.remove(d)
return False
return dfs(0, 0, 0, set(), {})
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
## https://leetcode.com/problems/verbal-arithmetic-puzzle/discuss/463921/python-backtracking-with-pruning-tricks
## from low digit position to high digit position, stop searching once (left side sum)%10 did not equal right side at current digit
## mark all initial characters, because not leading zeros are allowed.
start = set()
for word in words + [result]:
if len(word) > 1: ## note: a single 0 is allowed
start.add(word[0])
## find the maximum length between all words and result
n = max(list(map(len, words + [result])))
if len(result) < n: ## if the length of result is shorter than other words, it's not possible
return False
## helper function:
## idx: the index currently processing (of words and result)
## i: i-th word in words; when i == len(words) + 1: we have processed all words + result at index
## carry: the carry computed by summing all previous indexes of words
def dfs(idx, i, carry, visited, mp):
## base case: when we reach the highest digit (most significant) position
## we should have carry == 0, otherwise the sums are not equal
if idx == n:
return carry == 0
## when i == len(words) + 1: we have processed all words + result at index
## the specific index of word is word[-idx - 1]
## we check the sum added by carry
## if the sum does not match the digit at result[-idx - 1]
## return False
if i == len(words) + 1:
sums = sum(mp[word[-idx - 1]] if idx < len(word) else 0 for word in words) + carry
if sums % 10 == mp[result[-idx - 1]]:
carry = sums // 10 ## update carry to the next index
## recursive call to the next index and start from 0-th word
return dfs(idx + 1, 0, carry, visited, mp)
return False
## if current word (i-th) has shorter length than index,
## skip it, it will be counted as 0 for this digit
if (i < len(words) and idx >= len(words[i])):
return dfs(idx, i + 1, carry, visited, mp)
tmp = words + [result]
ch = tmp[i][-idx-1] ## current character
if ch in mp: ## if this character has been assigned a value
return dfs(idx, i + 1, carry, visited, mp)
## backtrack: try every possible digit
begin = 0
if ch in start:
begin = 1 ## if it is an initial character of some word
for x in range(begin, 10):
if x not in visited:
visited.add(x)
mp[ch] = x
if dfs(idx, i + 1, carry, visited, mp.copy()):
return True
visited.remove(x)
return False
return dfs(0, 0, 0, set(), {})
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
n = len(words)
mapper = {}
maxlen = 0
for w in words:
maxlen = max(maxlen, len(w))
for c in w:
mapper[c] = -1
if len(result) < maxlen or len(result) - maxlen > 1:
return False
for c in result:
mapper[c] = -1
used = [0] * 10
def solve(i, j, s):
if j == n or i == len(result) + 1:
l = len(result) - i
if l < 0:
if s != 0:
return False
if any(mapper[w[0]] == 0 for w in words):
return False
if mapper[result[0]] == 0:
return False
return True
c, s = divmod(s, 10)
if mapper[result[l]] >= 0:
if mapper[result[l]] == s:
return solve(i + 1, 0, c)
return False
if used[s]:
return False
mapper[result[l]] = s
used[s] = 1
res = solve(i + 1, 0, c)
mapper[result[l]] = -1
used[s] = 0
return res
w = words[j]
l = len(w) - i
if l < 0:
return solve(i, j + 1, s)
if mapper[w[l]] >= 0:
return solve(i, j + 1, s + mapper[w[l]])
for k in range(10):
if used[k]:
continue
used[k] = 1
mapper[w[l]] = k
if solve(i, j + 1, s + k):
return True
used[k] = 0
mapper[w[l]] = -1
return False
return solve(1, 0, 0)
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
start = set()
for word in words + [result]:
if len(word) > 1:
start.add(word[0])
n = max(map(len, words + [result]))
if len(result) < n:
return False
def dfs(idx, i, carry, visited, mp):
if idx == n:
return carry == 0
if i == len(words) + 1:
sums = sum(mp[word[-idx - 1]] if idx < len(word) else 0 for word in words) + carry
if sums % 10 == mp[result[-idx - 1]]:
carry = sums // 10
return dfs(idx + 1, 0, carry, visited, mp)
return False
if (i < len(words) and idx >= len(words[i])):
return dfs(idx, i + 1, carry, visited, mp)
tmp = words + [result]
ch = tmp[i][-idx-1]
if ch in mp:
return dfs(idx, i + 1, carry, visited, mp)
begin = 0
if ch in start:
begin = 1
for x in range(begin, 10):
if x not in visited:
visited.add(x)
mp[ch] = x
if dfs(idx, i + 1, carry, visited, mp.copy()):
return True
visited.remove(x)
return False
return dfs(0, 0, 0, set(), {})
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
start = set()
for word in words + [result]:
if len(word) > 1:
start.add(word[0])
n = max(map(len, words + [result]))
if len(result) < n:
return False
def dfs(idx, i, carry, visited, mp):
if idx == n:
return carry == 0
if i == len(words) + 1:
sums = sum(mp[word[-idx - 1]] if idx < len(word) else 0 for word in words) + carry
if sums % 10 == mp[result[-idx - 1]]:
carry = sums // 10
return dfs(idx + 1, 0, carry, visited, mp)
return False
if (i < len(words) and idx >= len(words[i])):
return dfs(idx, i + 1, carry, visited, mp)
tmp = words + [result]
ch = tmp[i][-idx-1]
if ch in mp:
return dfs(idx, i + 1, carry, visited, mp)
begin = 0
if ch in start:
begin = 1
for x in range(begin, 10):
if x not in visited:
visited.add(x)
mp[ch] = x
if dfs(idx, i + 1, carry, visited, mp.copy()):
return True
visited.remove(x)
return False
return dfs(0, 0, 0, set(), {})
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
from itertools import permutations
class Solution:
digitMap = {}
wordsRev = []
resultRev = []
limit = 0
def findSolution(self, n, carry = 0):
if n == self.limit:
# Check leading zero policy
leadingDigitChars = [w[len(w) - 1] for w in self.wordsRev]
leadingDigitChars.append(self.resultRev[len(self.resultRev) - 1])
leadingDigits = [self.digitMap[c] for c in leadingDigitChars]
return 0 not in leadingDigits
availableDigits = [n for n in range(0, 10) if n not in self.digitMap.values()]
digitChars = [w[n] for w in self.wordsRev if n < len(w)]
resultChar = self.resultRev[n]
knownDigitChars = list(filter(lambda x: x in self.digitMap, digitChars))
unknownDigitChars = [w for w in digitChars if w not in knownDigitChars]
digits = []
resultDigit = -1
if len(knownDigitChars) > 0:
digits = [self.digitMap[k] for k in knownDigitChars]
if resultChar in self.digitMap:
resultDigit = self.digitMap[resultChar]
for d in permutations(availableDigits, len(unknownDigitChars)):
s = sum(digits) + sum(d) + carry
c = int(s / 10)
s %= 10
if resultDigit >= 0 and s == resultDigit:
for i, v in enumerate(d):
self.digitMap[unknownDigitChars[i]] = v
if self.findSolution(n+1, c):
return True
else:
# Fallback
for i, v in enumerate(d):
if unknownDigitChars[i] in self.digitMap:
del self.digitMap[unknownDigitChars[i]]
elif resultDigit < 0 and ((resultChar not in unknownDigitChars and s not in d) or (resultChar in unknownDigitChars and s in d)) and s in availableDigits:
for i, v in enumerate(d):
self.digitMap[unknownDigitChars[i]] = v
if resultChar not in unknownDigitChars:
self.digitMap[resultChar] = s
elif s != self.digitMap[resultChar]:
for i, v in enumerate(d):
if unknownDigitChars[i] in self.digitMap:
del self.digitMap[unknownDigitChars[i]]
continue
if self.findSolution(n+1, c):
return True
else:
# Fallback
for i, v in enumerate(d):
if unknownDigitChars[i] in self.digitMap:
del self.digitMap[unknownDigitChars[i]]
if resultChar in self.digitMap:
del self.digitMap[resultChar]
return False
def isSolvable(self, words: List[str], result: str) -> bool:
self.digitMap = {}
self.wordsRev = [w[::-1] for w in words]
self.resultRev = result[::-1]
wordMax = max([len(w) for w in words])
if wordMax > len(result):
return False
self.limit = max(wordMax, len(result))
return self.findSolution(0, 0)
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
from collections import defaultdict
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
def search(i: int, j: int, carry: int, used: int, ls: list, mp: defaultdict, non_zeros: set) -> bool:
if j == len(ls[-1]):
return carry == 0
if i == len(ls):
total = sum([mp[ls[r][j]] if j < len(ls[r]) else 0 for r in range(len(ls) - 1)]) + carry
exp_total = mp[ls[-1][j]]
if (total % 10) != exp_total:
return False
return search(0, j + 1, total // 10, used, ls, mp, non_zeros)
if j >= len(ls[i]) or ls[i][j] in mp:
return search(i + 1, j, carry, used, ls, mp, non_zeros)
start = 1 if ls[i][j] in non_zeros else 0
for d in range(start, 10):
if (1 << d) & used:
continue
mp[ls[i][j]] = d
if search(i + 1, j, carry, used | (1 << d), ls, mp, non_zeros):
mp.pop(ls[i][j])
return True
mp.pop(ls[i][j])
return False
non_zeros = set([w[0] for w in words] + [result[0]])
ls = [w[::-1] for w in words] + [result[::-1]]
return search(0, 0, 0, 0, ls, defaultdict(int), non_zeros)
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
allWords = words + [result]
firstChars = set(word[0] for word in allWords)
maxWordLength = max(list(map(len, allWords)))
if len(result) < maxWordLength: return False
def dfs(charIdx, wordIdx, carry, visited, char2Digit):
# check if the final sum is equal
if charIdx == maxWordLength:
return carry == 0
# if we have assigned digits to all chars at the current index
# check if the assigned values work
if wordIdx == len(allWords):
sums = sum(char2Digit[word[-charIdx-1]] if charIdx < len(word) else 0 for word in words)
sums += carry
if sums % 10 == char2Digit[result[-charIdx-1]]:
return dfs(charIdx + 1, 0, sums // 10, visited, char2Digit)
else:
return False
# if the current char index is longer than the current word, move to the next word
currWord = allWords[-wordIdx-1]
if charIdx >= len(currWord):
return dfs(charIdx, wordIdx+1, carry, visited, char2Digit)
# if we already have a digit assignment for the char, skip it
currChar = currWord[-charIdx-1]
if currChar in char2Digit:
return dfs(charIdx, wordIdx+1, carry, visited, char2Digit)
# otherwise try every possible digit
else:
startDigit = 1 if currChar in firstChars else 0
for digit in range(startDigit, 10):
# skip previously assigned digits
if digit in list(char2Digit.values()): continue
# try the assignment
visited.add(digit)
char2Digit[currChar] = digit
if dfs(charIdx, wordIdx, carry, visited, char2Digit.copy()):
return True
visited.remove(digit)
return False
return dfs(0, 0, 0, set(), {})
|
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).
Return True if the equation is solvable otherwise return False.
Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true
Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false
Constraints:
2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.
|
class Solution:
def isSolvable(self, words: List[str], result: str) -> bool:
self.n = len(result)
self.levels = []
self.alldigit = {}
self.allch = []
self.result = result
self.nonzero = set()
for w in words:
self.nonzero.add(w[0])
self.nonzero.add(result[0])
# print(\"nonzero\", self.nonzero)
for r in range(len(result)):
l = []
for w in words:
if r < len(w):
l.append(w[len(w) - r - 1])
l.append(result[len(result) - 1 - r])
self.levels.append(l)
# print(\"levels\", self.levels)
self.occupy = set()
self.checkdigit = {} # num of words to digit
if len(self.levels[-1]) == 1:
self.alldigit[self.levels[-1][0]] = 1
self.occupy.add(1)
for l in range(len(self.levels)):
newch = set(self.levels[l]) - set(self.allch)
self.allch.extend(newch)
self.checkdigit[len(self.allch)] = l + 1
# print(\"checkdigit\", self.checkdigit)
# print(\"allch\", self.allch)
if self.tryone(0, len(self.allch)):
# print(self.alldigit)
return True
else:
# print(self.alldigit)
return False
def tryone(self, level, maxl):
flag = False
if maxl == level:
if self.check(self.checkdigit[level]):
# print(\"final level\", self.alldigit)
return True
else:
return False
if level in self.checkdigit:
if not self.check(self.checkdigit[level]):
return False
else:
pass
# if 'T' in self.alldigit and self.alldigit['T'] == 9 and level > 7:
# flag = True
# print(\"level:\", level, self.alldigit)
if self.allch[level] in self.alldigit:
if self.tryone(level + 1, maxl):
return True
else:
return False
for i in range(10):
if i not in self.occupy:
if i != 0 or self.allch[level] not in self.nonzero:
# if flag:
# print(\"level 8:\", level, i, self.allch[level])
self.occupy.add(i)
self.alldigit[self.allch[level]] = i
if self.tryone(level + 1, maxl):
return True
del self.alldigit[self.allch[level]]
self.occupy.remove(i)
return False
def check(self, level):
# flag = False
# if level > 5 and self.alldigit['I'] == 1 and self.alldigit['T'] >= 5:
# flag = True
# print(self.alldigit)
# if self.alldigit['Y'] > 1 and self.alldigit['D'] > 6 and self.alldigit['E'] > 4:
# flag = True
# print(\"check level\", level, self.alldigit)
plus = 0
# if level == 5 and self.alldigit['F'] == 1 and self.alldigit['U'] == 9:
# flag = True
# print(\"digit:\", level, self.alldigit)
for i in range(level):
levelsum = 0
for j in range(len(self.levels[i]) - 1):
levelsum += self.alldigit[self.levels[i][j]]
# if flag:
# print(\"level, levelsum, plus, result\", level, levelsum, plus, self.alldigit[self.levels[i][-1]])
if (levelsum + plus) % 10 != self.alldigit[self.levels[i][-1]]:
# if flag:
# print(\"False\")
return False
else:
plus = int((levelsum + plus)/10)
# if flag:
# print(\"plus\", plus)
# if flag:
# print(\"True\")
return True
|
The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagaram:
A chess knight can move as indicated in the chess diagram below:
We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell).
Given an integer n, return how many distinct phone numbers of length n we can dial.
You are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n. All jumps should be valid knight jumps.
As the answer may be very large, return the answer modulo 109 + 7.
Example 1:
Input: n = 1
Output: 10
Explanation: We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.
Example 2:
Input: n = 2
Output: 20
Explanation: All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]
Example 3:
Input: n = 3
Output: 46
Example 4:
Input: n = 4
Output: 104
Example 5:
Input: n = 3131
Output: 136006598
Explanation: Please take care of the mod.
Constraints:
1 <= n <= 5000
|
class Solution:
dp = [[1] * 10]
def knightDialer(self, n: int) -> int:
MOD = 10 ** 9 + 7
jump = [[4, 6], [6, 8], [7, 9], [4, 8], [3, 9, 0], [], [0, 1, 7], [2, 6], [1, 3], [2, 4]]
for i in range(len(self.dp), n):
new = [0] * 10
for j in range(10):
new[j] = sum(self.dp[-1][k] for k in jump[j]) % MOD
self.dp.append(new)
return sum(self.dp[n - 1]) % MOD
|
The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagaram:
A chess knight can move as indicated in the chess diagram below:
We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell).
Given an integer n, return how many distinct phone numbers of length n we can dial.
You are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n. All jumps should be valid knight jumps.
As the answer may be very large, return the answer modulo 109 + 7.
Example 1:
Input: n = 1
Output: 10
Explanation: We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.
Example 2:
Input: n = 2
Output: 20
Explanation: All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]
Example 3:
Input: n = 3
Output: 46
Example 4:
Input: n = 4
Output: 104
Example 5:
Input: n = 3131
Output: 136006598
Explanation: Please take care of the mod.
Constraints:
1 <= n <= 5000
|
from functools import lru_cache
mapping = [
[4, 6], # 0
[6, 8], # 1
[7, 9], # 2
[4, 8], # 3
[0, 3, 9], # 4
[], # 5
[0, 1, 7], # 6
[2, 6], # 7
[1, 3], # 8
[2, 4] # 9
]
mod = 1000_000_007
@lru_cache(None)
def dfs(n, i):
if n == 1:
return 1
sum_ = 0
for nei in mapping[i]:
sum_ = (sum_ + dfs(n -1, nei)) % mod
return sum_
class Solution:
def knightDialer(self, N: int) -> int:
total = 0
for i in range(10):
total = (total + dfs(N, i)) % mod
return total
|
The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagaram:
A chess knight can move as indicated in the chess diagram below:
We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell).
Given an integer n, return how many distinct phone numbers of length n we can dial.
You are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n. All jumps should be valid knight jumps.
As the answer may be very large, return the answer modulo 109 + 7.
Example 1:
Input: n = 1
Output: 10
Explanation: We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.
Example 2:
Input: n = 2
Output: 20
Explanation: All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]
Example 3:
Input: n = 3
Output: 46
Example 4:
Input: n = 4
Output: 104
Example 5:
Input: n = 3131
Output: 136006598
Explanation: Please take care of the mod.
Constraints:
1 <= n <= 5000
|
import numpy as np
class Solution:
def knightDialer(self, n: int) -> int:
# d = {1:[6,8],
# 2:[7,9],
# 3:[4,8],
# 4:[3,9,0],
# 5:[],
# 6:[1,7,0],
# 7:[2,6],
# 8:[1,3],
# 9:[2,4],
# 0:[4,6]}
# @lru_cache(None)
# def dfs(i, n):
# if n == 1:
# return 1
# else:
# res = 0
# for c in d[i]:
# res += dfs(c, n-1)
# return res % (10**9+7)
# return sum(dfs(i, n) for i in range(10)) % (10**9+7)
mod = 10**9 + 7
N = n
if N == 1: return 10
M = np.matrix([[0, 0, 0, 0, 1, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 0, 1],
[0, 0, 0, 0, 1, 0, 0, 0, 1, 0],
[1, 0, 0, 1, 0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 1, 0, 0, 0, 1, 0, 0, 0],
[0, 1, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 1, 0, 0, 0, 0, 0]])
res, N = 1, N - 1
while N:
if N % 2: res = res * M % mod
M = M * M % mod
N //= 2
return int(np.sum(res)) % mod
|
The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagaram:
A chess knight can move as indicated in the chess diagram below:
We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell).
Given an integer n, return how many distinct phone numbers of length n we can dial.
You are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n. All jumps should be valid knight jumps.
As the answer may be very large, return the answer modulo 109 + 7.
Example 1:
Input: n = 1
Output: 10
Explanation: We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.
Example 2:
Input: n = 2
Output: 20
Explanation: All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]
Example 3:
Input: n = 3
Output: 46
Example 4:
Input: n = 4
Output: 104
Example 5:
Input: n = 3131
Output: 136006598
Explanation: Please take care of the mod.
Constraints:
1 <= n <= 5000
|
class Solution:
def knightDialer(self, n: int) -> int:
# dp[neigh] at step k += dp[curr]
possibleMoves = [[4,6], [6,8],[9,7],[4,8],[0,3,9],[],[0,1,7],[2,6],[1,3], [2,4]]
dp = [1]*10
upper = 10**9 + 7
for i in range(n-1):
dp2 = [0]*10
for j in range(10):
for adj in possibleMoves[j]:
dp2[adj] = (dp2[adj] + dp[j])%upper
dp = dp2
return sum(dp)%upper
|
The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagaram:
A chess knight can move as indicated in the chess diagram below:
We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell).
Given an integer n, return how many distinct phone numbers of length n we can dial.
You are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n. All jumps should be valid knight jumps.
As the answer may be very large, return the answer modulo 109 + 7.
Example 1:
Input: n = 1
Output: 10
Explanation: We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.
Example 2:
Input: n = 2
Output: 20
Explanation: All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]
Example 3:
Input: n = 3
Output: 46
Example 4:
Input: n = 4
Output: 104
Example 5:
Input: n = 3131
Output: 136006598
Explanation: Please take care of the mod.
Constraints:
1 <= n <= 5000
|
class Solution:
def knightDialer(self, N: int) -> int:
table = [[0 for col in range(10)] for row in range(N+1)]
for val in range(10):
table[1][val] = 1
for i in range(2,N+1):
table[i][0] = table[i-1][4] + table[i-1][6]
table[i][1] = table[i-1][6] + table[i-1][8]
table[i][2] = table[i-1][7] + table[i-1][9]
table[i][3] = table[i-1][4] + table[i-1][8]
table[i][4] = table[i-1][3] + table[i-1][9] + table[i-1][0]
table[i][5] = 0
table[i][6] = table[i-1][7] + table[i-1][1] + table[i-1][0]
table[i][7] = table[i-1][2] + table[i-1][6]
table[i][8] = table[i-1][1] + table[i-1][3]
table[i][9] = table[i-1][2] + table[i-1][4]
return sum(table[-1])%(10**9 + 7)
|
The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagaram:
A chess knight can move as indicated in the chess diagram below:
We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell).
Given an integer n, return how many distinct phone numbers of length n we can dial.
You are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n. All jumps should be valid knight jumps.
As the answer may be very large, return the answer modulo 109 + 7.
Example 1:
Input: n = 1
Output: 10
Explanation: We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.
Example 2:
Input: n = 2
Output: 20
Explanation: All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]
Example 3:
Input: n = 3
Output: 46
Example 4:
Input: n = 4
Output: 104
Example 5:
Input: n = 3131
Output: 136006598
Explanation: Please take care of the mod.
Constraints:
1 <= n <= 5000
|
class Solution:
def knightDialer(self, n: int) -> int:
move = {1:[6,8], 2:[7,9], 3:[4,8], 4:[0,3,9], 5:[], 6:[0,1,7], 7:[2,6], 8:[1,3], 9:[2,4], 0:[4,6]}
curr_dial = [1] * 10
for _ in range(n-1):
next_dial = [0] * 10
for key in range(10):
for neighbor in move[key]:
next_dial[neighbor] = (next_dial[neighbor] + curr_dial[key]) % (10 ** 9 +7)
curr_dial = next_dial
return sum(curr_dial) % (10 ** 9 +7)
# case = set()
# def dfs(curr = \"\", k = 0):
# if k == n:
# case.add(curr)
# return
# if k == 0:
# for i in range(10):
# dfs(curr + str(i), k+1)
# else:
# for i in move[int(curr[-1])]:
# dfs(curr + str(i), k+1)
# dfs()
# return len(case) % (10 ** 9 +7)
|
The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagaram:
A chess knight can move as indicated in the chess diagram below:
We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell).
Given an integer n, return how many distinct phone numbers of length n we can dial.
You are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n. All jumps should be valid knight jumps.
As the answer may be very large, return the answer modulo 109 + 7.
Example 1:
Input: n = 1
Output: 10
Explanation: We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.
Example 2:
Input: n = 2
Output: 20
Explanation: All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]
Example 3:
Input: n = 3
Output: 46
Example 4:
Input: n = 4
Output: 104
Example 5:
Input: n = 3131
Output: 136006598
Explanation: Please take care of the mod.
Constraints:
1 <= n <= 5000
|
class Solution:
def knightDialer(self, N: int) -> int:
# Space O(10)
moves = [[4,6],[6,8],[7,9],[4,8],[3,9,0],[],[1,7,0],[2,6],[1,3],[2,4]]
dp = [1] * 10
MOD = 10**9 + 7
for i in range(N - 1):
next_dp = [0] * 10
for j in range(10):
for next_digit in moves[j]:
next_dp[j] = (next_dp[j] + dp[next_digit]) % MOD
dp = next_dp
return sum(dp) % MOD
# space O(10 * N)
mapping = {1:[6,8],
2:[7,9],
3:[4,8],
4:[3,9,0],
5:[],
6:[1,7,0],
7:[2,6],
8:[1,3],
9:[2,4],
0:[4,6]}
dp = [[1] * 10 for _ in range(N)]
dp[0] = [1] * 10
for i in range(1, N):
for j in range(10):
for k in mapping[j]:
dp[i][j] += dp[i - 1][k]
return sum(dp[-1]) % (10 ** 9 + 7)
|
The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagaram:
A chess knight can move as indicated in the chess diagram below:
We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell).
Given an integer n, return how many distinct phone numbers of length n we can dial.
You are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n. All jumps should be valid knight jumps.
As the answer may be very large, return the answer modulo 109 + 7.
Example 1:
Input: n = 1
Output: 10
Explanation: We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.
Example 2:
Input: n = 2
Output: 20
Explanation: All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]
Example 3:
Input: n = 3
Output: 46
Example 4:
Input: n = 4
Output: 104
Example 5:
Input: n = 3131
Output: 136006598
Explanation: Please take care of the mod.
Constraints:
1 <= n <= 5000
|
class Solution:
def knightDialer(self, n: int) -> int:
moves = [
[4, 6],
[6, 8],
[7, 9],
[4, 8],
[0, 3, 9],
[],
[0, 1, 7],
[2, 6],
[1, 3],
[2, 4],
]
kmod = 10**9 + 7
dp = [1] * 10
for k in range(1, n):
tmp = [0] * 10
for i in range(10):
for j in moves[i]:
tmp[j] = (tmp[j] + dp[i]) % kmod
dp = tmp
res = 0
for i in range(10):
res = (res + dp[i]) % kmod
return res
|
The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagaram:
A chess knight can move as indicated in the chess diagram below:
We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell).
Given an integer n, return how many distinct phone numbers of length n we can dial.
You are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n. All jumps should be valid knight jumps.
As the answer may be very large, return the answer modulo 109 + 7.
Example 1:
Input: n = 1
Output: 10
Explanation: We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.
Example 2:
Input: n = 2
Output: 20
Explanation: All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]
Example 3:
Input: n = 3
Output: 46
Example 4:
Input: n = 4
Output: 104
Example 5:
Input: n = 3131
Output: 136006598
Explanation: Please take care of the mod.
Constraints:
1 <= n <= 5000
|
class Solution:
def knightDialer(self, n: int) -> int:
valid_moves = [
[4, 6],
[6, 8],
[7, 9],
[4, 8],
[0, 3, 9],
[],
[0, 1, 7],
[2, 6],
[1, 3],
[2, 4]
]
dp = [1] * 10
m = 10 ** 9 + 7
for _ in range(n-1):
new_dp = [0] * 10
for i in range(10):
for j in valid_moves[i]:
new_dp[j] += dp[i] % m
dp = new_dp
return sum(dp) % m
|
The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagaram:
A chess knight can move as indicated in the chess diagram below:
We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell).
Given an integer n, return how many distinct phone numbers of length n we can dial.
You are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n. All jumps should be valid knight jumps.
As the answer may be very large, return the answer modulo 109 + 7.
Example 1:
Input: n = 1
Output: 10
Explanation: We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.
Example 2:
Input: n = 2
Output: 20
Explanation: All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]
Example 3:
Input: n = 3
Output: 46
Example 4:
Input: n = 4
Output: 104
Example 5:
Input: n = 3131
Output: 136006598
Explanation: Please take care of the mod.
Constraints:
1 <= n <= 5000
|
class Solution:
def knightDialer(self, N: int) -> int:
moves = [(4,6),(6,8),(7,9),(4,8),(3,9,0),(),(1,7,0),(2,6),(1,3),(2,4)]
memo = [1]*10
maxV = (10**9+7)
for _ in range(N-1):
temp = [0]*10
for i in range(10):
for dest in moves[i]:
temp[i] += memo[dest]
temp[i] %= (10**9+7)
memo = temp
return sum(memo)%(10**9+7)
|
The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagaram:
A chess knight can move as indicated in the chess diagram below:
We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell).
Given an integer n, return how many distinct phone numbers of length n we can dial.
You are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n. All jumps should be valid knight jumps.
As the answer may be very large, return the answer modulo 109 + 7.
Example 1:
Input: n = 1
Output: 10
Explanation: We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.
Example 2:
Input: n = 2
Output: 20
Explanation: All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]
Example 3:
Input: n = 3
Output: 46
Example 4:
Input: n = 4
Output: 104
Example 5:
Input: n = 3131
Output: 136006598
Explanation: Please take care of the mod.
Constraints:
1 <= n <= 5000
|
class Solution:
def knightDialer(self, n: int) -> int:
MOD = 10**9 + 7
#dp[i][j] possible answers at step[i], number j
dp =[0 for _ in range(10)]
#possible next moves
move = [[4,6], [6,8], [7,9], [4,8], [3,9,0], [], [1,7,0], [2,6], [1,3], [4,2]]
#noundary condition, initialization at n = 0, dp[0][j] = 1
dp = [1 for _ in range(10)]
#transfer equation
for i in range(n-1):
dp2 = [0]*10
for j in range(10):
for nei in move[j]:
dp2[nei] = (dp2[nei] + dp[j])%MOD
dp = dp2
#final answer
return sum(dp)%MOD
|
The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagaram:
A chess knight can move as indicated in the chess diagram below:
We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell).
Given an integer n, return how many distinct phone numbers of length n we can dial.
You are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n. All jumps should be valid knight jumps.
As the answer may be very large, return the answer modulo 109 + 7.
Example 1:
Input: n = 1
Output: 10
Explanation: We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.
Example 2:
Input: n = 2
Output: 20
Explanation: All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]
Example 3:
Input: n = 3
Output: 46
Example 4:
Input: n = 4
Output: 104
Example 5:
Input: n = 3131
Output: 136006598
Explanation: Please take care of the mod.
Constraints:
1 <= n <= 5000
|
class Solution:
def knightDialer(self, n: int) -> int:
movements = {
0:(4,6),
1:(6,8),
2:(7,9),
3:(4,8),
4:(0,3,9),
5:(),
6:(0,1,7),
7:(2,6),
8:(1,3),
9:(2,4)
}
total = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
for _ in range(n - 1):
curr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
for num in range(10):
for move in movements[num]:
curr[move] = (curr[move] + total[num]) % (10 ** 9 + 7)
total = curr
return sum(total) % (10**9 + 7)
|
The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagaram:
A chess knight can move as indicated in the chess diagram below:
We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell).
Given an integer n, return how many distinct phone numbers of length n we can dial.
You are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n. All jumps should be valid knight jumps.
As the answer may be very large, return the answer modulo 109 + 7.
Example 1:
Input: n = 1
Output: 10
Explanation: We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.
Example 2:
Input: n = 2
Output: 20
Explanation: All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]
Example 3:
Input: n = 3
Output: 46
Example 4:
Input: n = 4
Output: 104
Example 5:
Input: n = 3131
Output: 136006598
Explanation: Please take care of the mod.
Constraints:
1 <= n <= 5000
|
import numpy as np
class Solution:
def knightDialer(self, N: int) -> int:
mod = 10**9 + 7
moves = np.matrix([[0, 0, 0, 0, 1, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 0, 1],
[0, 0, 0, 0, 1, 0, 0, 0, 1, 0],
[1, 0, 0, 1, 0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 1, 0, 0, 0, 1, 0, 0, 0],
[0, 1, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 1, 0, 0, 0, 0, 0]])
res = np.matrix([[1]*10])
N -= 1
while N:
if N % 2 != 0:
res = res * moves % mod
N -= 1
else:
moves = moves * moves % mod
N //= 2
return int(np.sum(res)) % mod
|
The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagaram:
A chess knight can move as indicated in the chess diagram below:
We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell).
Given an integer n, return how many distinct phone numbers of length n we can dial.
You are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n. All jumps should be valid knight jumps.
As the answer may be very large, return the answer modulo 109 + 7.
Example 1:
Input: n = 1
Output: 10
Explanation: We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.
Example 2:
Input: n = 2
Output: 20
Explanation: All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]
Example 3:
Input: n = 3
Output: 46
Example 4:
Input: n = 4
Output: 104
Example 5:
Input: n = 3131
Output: 136006598
Explanation: Please take care of the mod.
Constraints:
1 <= n <= 5000
|
class Solution:
def knightDialer(self, n: int) -> int:
mod = 10**9+7
next_dic = {}
next_dic[1] = [8,6]
next_dic[2] = [7,9]
next_dic[3] = [4,8]
next_dic[4] = [3,9,0]
next_dic[5] = []
next_dic[6] = [7,1,0]
next_dic[7] = [2,6]
next_dic[8] = [3,1]
next_dic[9] = [2,4]
next_dic[0] = [6,4]
dp = [1]*10
for i in range(n-1):
dp_new = [0]*10
for i in range(10):
for move in next_dic[i]:
dp_new[move] = (dp_new[move]+dp[i])%mod
del dp
dp = dp_new
return sum(dp)%mod
|
The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagaram:
A chess knight can move as indicated in the chess diagram below:
We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell).
Given an integer n, return how many distinct phone numbers of length n we can dial.
You are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n. All jumps should be valid knight jumps.
As the answer may be very large, return the answer modulo 109 + 7.
Example 1:
Input: n = 1
Output: 10
Explanation: We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.
Example 2:
Input: n = 2
Output: 20
Explanation: All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]
Example 3:
Input: n = 3
Output: 46
Example 4:
Input: n = 4
Output: 104
Example 5:
Input: n = 3131
Output: 136006598
Explanation: Please take care of the mod.
Constraints:
1 <= n <= 5000
|
class Solution:
def knightDialer(self, n: int) -> int:
# Neighbors maps K: starting_key -> V: list of possible destination_keys
neighbors = {
0:(4,6),
1:(6,8),
2:(7,9),
3:(4,8),
4:(0,3,9),
5:(),
6:(0,1,7),
7:(2,6),
8:(1,3),
9:(2,4)
}
current_counts = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
for _ in range(n-1):
next_counts = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
for src_key in range(10):
for dst_key in neighbors[src_key]:
next_counts[dst_key] = (next_counts[dst_key] + current_counts[src_key]) % (10**9 + 7)
current_counts = next_counts
return sum(current_counts) % (10**9 + 7)
|
The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagaram:
A chess knight can move as indicated in the chess diagram below:
We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell).
Given an integer n, return how many distinct phone numbers of length n we can dial.
You are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n. All jumps should be valid knight jumps.
As the answer may be very large, return the answer modulo 109 + 7.
Example 1:
Input: n = 1
Output: 10
Explanation: We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.
Example 2:
Input: n = 2
Output: 20
Explanation: All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]
Example 3:
Input: n = 3
Output: 46
Example 4:
Input: n = 4
Output: 104
Example 5:
Input: n = 3131
Output: 136006598
Explanation: Please take care of the mod.
Constraints:
1 <= n <= 5000
|
class Solution:
def knightDialer(self, N: int) -> int:
M = 10 ** 9 + 7
d = {1: [6, 8], 2: [7, 9], 3:[4, 8], 4: [3, 9, 0], 5: [],
6: [0, 1, 7], 7: [6, 2], 8: [1, 3], 9: [2, 4], 0: [4, 6]}
out = [1] * 10
for _ in range(N - 1):
out1 = [0] * 10
for j in range(10):
for k in d[j]:
out1[k] += out[j] % M
out = out1
return sum(out) % M
|
The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagaram:
A chess knight can move as indicated in the chess diagram below:
We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell).
Given an integer n, return how many distinct phone numbers of length n we can dial.
You are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n. All jumps should be valid knight jumps.
As the answer may be very large, return the answer modulo 109 + 7.
Example 1:
Input: n = 1
Output: 10
Explanation: We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.
Example 2:
Input: n = 2
Output: 20
Explanation: All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]
Example 3:
Input: n = 3
Output: 46
Example 4:
Input: n = 4
Output: 104
Example 5:
Input: n = 3131
Output: 136006598
Explanation: Please take care of the mod.
Constraints:
1 <= n <= 5000
|
class Solution:
def knightDialer(self, n: int) -> int:
mod = 10**9+7
dic = {0:[4,6], 1:[6,8], 2:[7,9], 3:[4,8], 4:[0,3,9], 5:[], 6:[0,1,7], 7:[2,6], 8:[1,3], 9:[4,2]}
counts = [1,1,1,1,1,1,1,1,1,1]
for k in range(n-1):
new = [0,0,0,0,0,0,0,0,0,0]
for i in range(10):
for j in dic[i]:
new[j] = (new[j]+counts[i])%mod
counts = new
return sum(counts)%mod
|
The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagaram:
A chess knight can move as indicated in the chess diagram below:
We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell).
Given an integer n, return how many distinct phone numbers of length n we can dial.
You are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n. All jumps should be valid knight jumps.
As the answer may be very large, return the answer modulo 109 + 7.
Example 1:
Input: n = 1
Output: 10
Explanation: We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.
Example 2:
Input: n = 2
Output: 20
Explanation: All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]
Example 3:
Input: n = 3
Output: 46
Example 4:
Input: n = 4
Output: 104
Example 5:
Input: n = 3131
Output: 136006598
Explanation: Please take care of the mod.
Constraints:
1 <= n <= 5000
|
class Solution:
def knightDialer(self, N: int) -> int:
# Neighbors maps K: starting_key -> V: list of possible destination_keys
neighbors = {
0:(4,6),
1:(6,8),
2:(7,9),
3:(4,8),
4:(0,3,9),
5:(),
6:(0,1,7),
7:(2,6),
8:(1,3),
9:(2,4)
}
current_counts = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
for _ in range(N-1):
next_counts = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
for src_key in range(10):
for dst_key in neighbors[src_key]:
next_counts[dst_key] = (next_counts[dst_key] + current_counts[src_key]) % (10**9 + 7)
current_counts = next_counts
return sum(current_counts) % (10**9 + 7)
|
The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagaram:
A chess knight can move as indicated in the chess diagram below:
We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell).
Given an integer n, return how many distinct phone numbers of length n we can dial.
You are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n. All jumps should be valid knight jumps.
As the answer may be very large, return the answer modulo 109 + 7.
Example 1:
Input: n = 1
Output: 10
Explanation: We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.
Example 2:
Input: n = 2
Output: 20
Explanation: All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]
Example 3:
Input: n = 3
Output: 46
Example 4:
Input: n = 4
Output: 104
Example 5:
Input: n = 3131
Output: 136006598
Explanation: Please take care of the mod.
Constraints:
1 <= n <= 5000
|
class Solution:
def knightDialer(self, n: int) -> int:
d = {1:(6, 8), 2:(7, 9), 3:(4,8), 4: (0, 3, 9), 5:(), 6: (0, 1, 7), 7:(2, 6), 8:(1, 3), 9:(2, 4), 0:(4,6)}
prev = [1] * 10
for dial in range(n - 1):
nex = [0] * 10
for curNum in range(10):
for nexNum in d[curNum]:
nex[nexNum] = (nex[nexNum] + prev[curNum]) % (10**9+ 7)
prev = nex [:]
return sum(prev)%(10**9+ 7)
|
The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagaram:
A chess knight can move as indicated in the chess diagram below:
We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell).
Given an integer n, return how many distinct phone numbers of length n we can dial.
You are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n. All jumps should be valid knight jumps.
As the answer may be very large, return the answer modulo 109 + 7.
Example 1:
Input: n = 1
Output: 10
Explanation: We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.
Example 2:
Input: n = 2
Output: 20
Explanation: All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]
Example 3:
Input: n = 3
Output: 46
Example 4:
Input: n = 4
Output: 104
Example 5:
Input: n = 3131
Output: 136006598
Explanation: Please take care of the mod.
Constraints:
1 <= n <= 5000
|
class Solution:
def knightDialer(self, n: int) -> int:
moves = [[4, 6],[6, 8],[7, 9],[4, 8]
,[0, 3, 9],[],[0, 1, 7]
,[2, 6],[1, 3],[2, 4]]
dp = [1] * 10
for _ in range(n-1):
dp2 = [0] * 10
for i, cnt in enumerate(dp):
for nxt in moves[i]:
dp2[nxt] += cnt
dp = dp2
return sum(dp) % (10**9 + 7)
|
The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagaram:
A chess knight can move as indicated in the chess diagram below:
We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell).
Given an integer n, return how many distinct phone numbers of length n we can dial.
You are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n. All jumps should be valid knight jumps.
As the answer may be very large, return the answer modulo 109 + 7.
Example 1:
Input: n = 1
Output: 10
Explanation: We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.
Example 2:
Input: n = 2
Output: 20
Explanation: All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]
Example 3:
Input: n = 3
Output: 46
Example 4:
Input: n = 4
Output: 104
Example 5:
Input: n = 3131
Output: 136006598
Explanation: Please take care of the mod.
Constraints:
1 <= n <= 5000
|
class Solution:
def knightDialer(self, n: int) -> int:
# time O(n); space O(1)
moves = [[4,6],[6,8],[7,9],[4,8],[3,9,0],[], [1,7,0],[2,6],[1,3],[2,4]]
dp = [1] * 10
for hop in range(n-1):
new_dp = [0] * 10
for node, cnt in enumerate(dp):
for nei in moves[node]:
new_dp[nei] += cnt
dp = new_dp
return sum(dp) % (10**9+7)
|
The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagaram:
A chess knight can move as indicated in the chess diagram below:
We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell).
Given an integer n, return how many distinct phone numbers of length n we can dial.
You are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n. All jumps should be valid knight jumps.
As the answer may be very large, return the answer modulo 109 + 7.
Example 1:
Input: n = 1
Output: 10
Explanation: We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.
Example 2:
Input: n = 2
Output: 20
Explanation: All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]
Example 3:
Input: n = 3
Output: 46
Example 4:
Input: n = 4
Output: 104
Example 5:
Input: n = 3131
Output: 136006598
Explanation: Please take care of the mod.
Constraints:
1 <= n <= 5000
|
class Solution:
def knightDialer1(self, N: int) -> int:
m,n = 4,3
M = 10**9+7
def dp(i,j,k):
if k==0:
return 1
out = 0
for x,y in [(i+2,j+1),(i-2,j+1),(i+2,j-1),(i-2,j-1),
(i+1,j+2),(i+1,j-2),(i-1,j+2),(i-1,j-2)]:
if 0<=x<m and 0<=y<n and (x!=3 or y not in [0,2]):
out += dp(x,y,k-1)
return out
out = 0
for i in range(m):
for j in range(n):
if i!=m-1 or j not in [0,2]:
out+=dp(i,j,N-1)
return out
def knightDialer(self, N: int) -> int:
M = 10**9+7
d = {1:[6,8],2:[7,9],3:[4,8],4:[3,9,0],5:[],6:[0,1,7],7:[6,2],8:[1,3],9:[2,4],0:[4,6]}
out = [1]*10
for i in range(N-1):
out1=[0]*10
for j in range(10):
for k in d[j]:
out1[k]+=out[j]%M
out=out1
return sum(out)%M
|
The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagaram:
A chess knight can move as indicated in the chess diagram below:
We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell).
Given an integer n, return how many distinct phone numbers of length n we can dial.
You are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n. All jumps should be valid knight jumps.
As the answer may be very large, return the answer modulo 109 + 7.
Example 1:
Input: n = 1
Output: 10
Explanation: We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.
Example 2:
Input: n = 2
Output: 20
Explanation: All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]
Example 3:
Input: n = 3
Output: 46
Example 4:
Input: n = 4
Output: 104
Example 5:
Input: n = 3131
Output: 136006598
Explanation: Please take care of the mod.
Constraints:
1 <= n <= 5000
|
class Solution:
def helper(self,cache,position,num_hops):
neighbors = [[4,6],[6,8],[7,9],[4,8],[3,9,0],[],
[1,7,0],[2,6],[1,3],[2,4]]
if (position, num_hops) in cache:
return cache[ (position, num_hops) ]
if num_hops == 0:
return 1
else:
num_sequences = 0
for neighbor in neighbors[position]:
num_sequences += self.helper(cache,neighbor, num_hops - 1)
cache[ (position, num_hops) ] = num_sequences
return num_sequences
def knightDialer(self, n: int) -> int:
neighbors = [[4,6],[6,8],[7,9],[4,8],[3,9,0],[],
[1,7,0],[2,6],[1,3],[2,4]]
prior_case = [1] * 10
current_case = [1] * 10
current_num_hops = 1
while current_num_hops < n:
current_case = [0] * 10
current_num_hops += 1
for position in range(0, 10):
for neighbor in neighbors[position]:
current_case[position] += prior_case[neighbor]
prior_case = current_case
return sum(current_case) % (10**9 + 7)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.