VOOZH about

URL: https://www.geeksforgeeks.org/dsa/length-of-longest-increasing-subsequences-lis-using-segment-tree/

⇱ Length of Longest Increasing Subsequences (LIS) using Segment Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Length of Longest Increasing Subsequences (LIS) using Segment Tree

Last Updated : 23 Jul, 2025

Given an array arr[] of size N, the task is to count the number of longest increasing subsequences present in the given array.

Example:

Input: arr[] = {2, 2, 2, 2, 2}
Output: 5
Explanation: The length of the longest increasing subsequence is 1, i.e. {2}. Therefore, count of longest increasing subsequences of length 1 is 5. 
 

Input: arr[] = {1, 3, 5, 4, 7}
Output: 2
Explanation: The length of the longest increasing subsequence is 4, and there are 2 longest increasing subsequences of length 4, i.e. {1, 3, 4, 7} and {1, 3, 5, 7}.

Approach: An approach to the given problem has been already discussed using dynamic programming in this article. 
This article suggests a different approach using segment trees. Follow the below steps to solve the given problem:

  • Initialise the segment tree as an array of pairs initially containing pairs of (0, 0), where the 1st element represents the length of LIS and 2nd element represents the count of LIS of current length.
  • The 1st element of the segment tree can be calculated similarly to the approach discussed in this article.
  • The 2nd element of the segment tree can be calculated using the following steps:
    • If cases where the length of left child > length of right child, the parent node becomes equal to the left child as LIS will that be of the left child.
    • If cases where the length of left child < length of right child, the parent node becomes equal to the right child as LIS will that be of the right child.
    • If cases where the length of left child = length of right child, the parent node becomes equal to the sum of the count of LIS of the left child and the right child.
  • The required answer is the 2nd element of the root of the segment tree.

Below is the implementation of the above approach:


Output
2

Time Complexity: O(N*log N)
Auxiliary Space: O(N)

Related Topic: Segment Tree

Comment