Difficulty: Easy | Acceptance: 49.50% | Paid: No Topics: Array
You are given a 0-indexed integer array nums. An array is called trionic if it consists of exactly three distinct elements and the sum of the first two elements equals the third element.
Return true if nums is a trionic array, otherwise return false.
- Examples
- Constraints
- Direct Conditional Check
- Set-based Validation
Examples
Example 1
Input:
nums = [1,3,5,4,2,6]
Output:
true
Explanation: Pick p = 2, q = 4:
nums[0…2] = [1, 3, 5] is strictly increasing (1 < 3 < 5).
nums[2…4] = [5, 4, 2] is strictly decreasing (5 > 4 > 2).
nums[4…5] = [2, 6] is strictly increasing (2 < 6).
Example 2
Input:
nums = [2,1,3]
Output:
false
Explanation: There is no way to pick p and q to form the required three segments.
Constraints
3 <= nums.length <= 100
1 <= nums[i] <= 100
Direct Conditional Check
Intuition We can verify the definition of a trionic array by explicitly checking the three required conditions: the array length must be 3, all elements must be distinct, and the sum of the first two must equal the third.
Steps
- Check if the length of
numsis exactly 3. If not, returnfalse. - Check if
nums[0],nums[1], andnums[2]are all distinct from each other. - Check if
nums[0] + nums[1] == nums[2]. - Return
trueonly if all checks pass.
from typing import List
class Solution:
def isTrionicArray(self, nums: List[int]) -> bool:
if len(nums) != 3:
return False
if nums[0] == nums[1] or nums[1] == nums[2] or nums[0] == nums[2]:
return False
return nums[0] + nums[1] == nums[2]
Complexity
- Time: O(1)
- Space: O(1)
- Notes: This is the most efficient approach as it avoids any overhead from data structures.
Set-based Validation
Intuition We can utilize a Set data structure to efficiently check for distinctness. By inserting all elements into a Set, we can verify if the count of unique elements is exactly 3.
Steps
- Check if the length of
numsis exactly 3. - Insert all elements of
numsinto a Set. - Check if the size of the Set is 3 (ensuring all elements are distinct).
- Check if
nums[0] + nums[1] == nums[2]. - Return
trueif all conditions are met.
from typing import List
class Solution:
def isTrionicArray(self, nums: List[int]) -> bool:
if len(nums) != 3:
return False
distinct_elements = set(nums)
if len(distinct_elements) != 3:
return False
return nums[0] + nums[1] == nums[2]
Complexity
- Time: O(1) - Since the array size is fixed at 3, operations are constant.
- Space: O(1) - The Set stores at most 3 integers.
- Notes: While functionally correct, this approach has slightly higher constant overhead than direct comparison.