Similar Problems

Similar Problems not available

Find Triangular Sum Of An Array - Leetcode Solution

Companies:

LeetCode:  Find Triangular Sum Of An Array Leetcode Solution

Difficulty: Medium

Topics: math array simulation  

Problem Statement:

Given a 2D integer array, find the sum of all the triangular subarrays. A triangular subarray is a subarray in the form of a triangle, i.e., it is formed by selecting a contiguous subset of elements in such a way that it forms a triangle when placed in a 2D plane.

Example:

Input: [[1,2,3], [4,5,6], [7,8,9]]

Output: 54

Explanation:

There are 10 triangular subarrays in the input array:

[1], [2], [3], [4], [5], [6], [7], [8], [9] and [1, 4, 7]

The sum of all these triangular subarrays is 54.

Solution:

The first step to solve this problem is to understand the definition of a triangular subarray. A triangular subarray is a subarray that forms a triangle when placed in a 2D plane. We can easily see that a subarray [a, b, c, d] can form a triangle if a < b < c < d or a > b > c > d.

We can use this observation to solve the problem. For each element in the array, we can find the number of triangular subarrays that can be formed with that element as the top or the bottom of the triangle. We can do this by counting the number of elements that are less than or greater than the current element in its row and column.

Let's take an example to understand this approach:

Input: [[1,2,3], [4,5,6], [7,8,9]]

We can start by considering each element in the array as the top or the bottom of the triangle and count the number of possible triangles that can be formed.

For each element, we can count the number of elements that are less than or greater than it in its row and column. For example, for element 5, we have:

Less than in row: None Greater than in row: [6] Less than in column: [1, 2, 3, 4] Greater than in column: [8, 9]

We can use this information to count the number of triangles that can be formed with 5 as the bottom of the triangle and with 5 as the top of the triangle.

For 5 as the bottom of the triangle, we have:

4 5 6

The number of triangles that can be formed with 5 as the bottom of the triangle is equal to the product of the number of elements that are less than or equal to 5 in its row and the number of elements that are greater than or equal to 5 in its column.

For 5 as the top of the triangle, we have:

5 2 6 1 4 9

The number of triangles that can be formed with 5 as the top of the triangle is equal to the product of the number of elements that are greater than or equal to 5 in its row and the number of elements that are less than or equal to 5 in its column.

We can repeat this process for each element in the array and sum up the number of triangles that can be formed.

The time complexity of this approach is O(N^3), where N is the size of the input array.

Find Triangular Sum Of An Array Solution Code

1