Sign of the Product of an Array — LeetCode 1822 Python Solution
EasyArrayMath
- Problem
- #1822
- Pattern
- Math and Number Theory
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Implement a function signFunc(x) that returns: 1 if x is positive. -1 if x is negative.
Example
- Input
- nums = [-1,-2,-3,-4,3,2,1]
- Output
- 1
- Explanation
- The product of all values in the array is 144, and signFunc(144) = 1
Python solution
Python
class Solution:
def arraySign(self, nums: List[int]) -> int:
ans = 1
for v in nums:
if v == 0:
return 0
if v < 0:
ans *= -1
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the array |
| Space | O(1) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 1822. Sign of the Product of an Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1822. Sign of the Product of an Array?
- LeetCode 1822. Sign of the Product of an Array is rated Easy on LeetCode.
- What is the time complexity of LeetCode 1822. Sign of the Product of an Array?
- The Python solution on this page runs in O(n), where n is the length of the array.
- What is the space complexity of LeetCode 1822. Sign of the Product of an Array?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1822. Sign of the Product of an Array cover?
- LeetCode 1822. Sign of the Product of an Array is tagged Array and Math on LeetCode.