EasyNo. 1822

Sign of the Product of an Array — LeetCode 1822 Python Solution

Topics
Array, Math
Reading time
2 min

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

PythonSolution
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 ans

Complexity

Time
O(n)where n is the length of the array
Space · auxiliary
O(1)

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

Related problems
No.ProblemDifficulty
1819Number of Different Subsequences GCDsHard
1828Queries on Number of Points Inside a CircleMedium
0048Rotate ImageMedium
0066Plus OneEasy
0189Rotate ArrayMedium
0204Count PrimesMedium

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.