Sum of Beauty in the Array — LeetCode 2012 Python Solution

MediumArray
Problem
#2012
Reading time
3 min

The problem

You are given a 0-indexed integer array nums. For each index i (1 <= i <= nums.length - 2) the beauty of nums[i] equals: 2, if nums[j] < nums[i] < nums[k], for all 0 <= j < i and for all i < k <= nums.length - 1.

Example

Input
nums = [1,2,3]
Output
2
Explanation
For each index i in the range 1 <= i <= 1:

Python solution

Python
class Solution:
    def sumOfBeauties(self, nums: List[int]) -> int:
        n = len(nums)
        right = [nums[-1]] * n
        for i in range(n - 2, -1, -1):
            right[i] = min(right[i + 1], nums[i])
        ans = 0
        l = nums[0]
        for i in range(1, n - 1):
            r = right[i + 1]
            if l < nums[i] < r:
                ans += 2
            elif nums[i - 1] < nums[i] < nums[i + 1]:
                ans += 1
            l = max(l, nums[i])
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 2012. Sum of Beauty in the Array?
LeetCode 2012. Sum of Beauty in the Array is rated Medium on LeetCode.
What is the time complexity of LeetCode 2012. Sum of Beauty in the Array?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2012. Sum of Beauty in the Array?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2012. Sum of Beauty in the Array cover?
LeetCode 2012. Sum of Beauty in the Array is tagged Array 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.

Get Stealth Interview