Similar Problems
Similar Problems not available
Design Excel Sum Formula - Leetcode Solution
Companies:
LeetCode: Design Excel Sum Formula Leetcode Solution
Difficulty: Hard
Topics: design matrix array graph
Problem:
Given a 2D array filled with integers, write an Excel sum formula that sums up all the numbers in the array.
The 2D array is given as follows:
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
The Excel sum formula should look like this:
=SUM(A1:C3)
Here, A1
represents the top-left cell of the array, and C3
represents the bottom-right cell of the array.
Solution:
To solve this problem, we need to follow these steps:
- Identify the top-left cell and the bottom-right cell of the array.
- Construct the Excel sum formula using the row and column indices of these cells.
- Return the Excel sum formula as the output.
Step 1: Identifying the top-left and bottom-right cells
In the given 2D array, the top-left cell is A1
, and the bottom-right cell is C3
. We can use the ROWS
and COLUMNS
functions to get the row and column count of the array, and use these counts to calculate the row and column indices of the top-left and bottom-right cells.
rows = len(arr)
cols = len(arr[0])
top_left_cell = 'A1'
bottom_right_cell = chr(ord('A') + cols - 1) + str(rows)
Here, ord('A')
returns the ASCII code of the character 'A', which is 65. We add cols - 1
to get the ASCII code of the last column, and then use chr()
to convert it back to a character. The result is chr(ord('A') + cols - 1)
. We then concatenate this character with the row count to get the cell address of the bottom-right cell.
Step 2: Constructing the Excel sum formula
Now that we have the cell addresses of the top-left and bottom-right cells, we can construct the Excel sum formula as follows:
excel_sum_formula = '=SUM(' + top_left_cell + ':' + bottom_right_cell + ')'
Here, we concatenate the SUM
function with the cell addresses of the top-left and bottom-right cells.
Step 3: Returning the output
Finally, we return the Excel sum formula as the output:
return excel_sum_formula
Putting it all together, we get the following solution:
def excel_sum_formula(arr):
# Step 1: Identify the top-left and bottom-right cells
rows = len(arr)
cols = len(arr[0])
top_left_cell = 'A1'
bottom_right_cell = chr(ord('A') + cols - 1) + str(rows)
# Step 2: Construct the Excel sum formula
excel_sum_formula = '=SUM(' + top_left_cell + ':' + bottom_right_cell + ')'
# Step 3: Return the output
return excel_sum_formula
We can test this function with the given example array:
arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(excel_sum_formula(arr))
The output should be:
=SUM(A1:C3)
Design Excel Sum Formula Solution Code
1