Skip to content
Related Articles

Related Articles

Find the Alpha Score of the Given Steps (Using BST)
  • Difficulty Level : Expert
  • Last Updated : 05 Nov, 2020
GeeksforGeeks - Summer Carnival Banner

Given an array A[] consisting of N numbers denoting the values written on N steps, the task is to find the alpha score of the total journey of climbing up all the stairs. Since the answer can be very large, print the answer modulo 109 + 7.

Alpha Score: The alpha score at each step is the sum of all the numbers previously seen on the stairs climbed which are smaller than the number on the current stair.
The alpha score of the total journey is the sum of the alpha scores of each step.

Examples: 

Input: A[] = {13, 14, 20}
Output: 87
Explanation:
Alpha Score at the first stair = 13
Alpha Score at the second stair = 13 + 14 = 27
Alpha Score of the third stair = 13 + 14 + 20 = 47          
Sum of all the Alpha Scores=13 + 27 + 47 = 87
Therefore, the Alpha Score of the total journey is 87.

Input: A[] = {10, 11, 12} 
Output: 64
Explanation: 
Alpha Score at the first stair = 10
Alpha Score at the second stair = 10 + 11 = 21
Alpha Score of the third stair = 10+11 + 12 = 33  
Sum of all the Alpha Scores =10 + 21 + 33
Therefore, the Alpha Score of the total journey is 64.



Naive Approach: 
The simplest approach to solve the problem is to traverse each element in the array and calculate the sum of all the elements smaller than the current element present at previous indices to calculate the Alpha Score of the current stair. For each sum calculated, update the total_sum(Alpha Score of the total journey). Finally, print the total_sum as the Alpha Score of the complete journey.

Time Complexity: O(N2)
Auxiliary Space: O(1) 

Efficient Approach: 
The above approach can be optimized using Binary Search Trees. Follow the steps below:

  • Sort the given array.
  • Construct a BST from the sorted array.
  • Recursively traverse the BST and follow the steps below:
    • Traverse the left subtree.
    • Add the value of the current node to sum (Alpha score for current stair) and update the total_sum (Alpha score of the journey till now).
    • Traverse the right subtree.
  • After complete traversal of the BST, print the total_sum.

Below is the implementation of the above approach:

C++




// C++ program to implement
// the above approach
#include<bits/stdc++.h>
using namespace std;
 
static long sum = 0, total_sum = 0;
static long mod = 1000000007;
 
// Structure of a node
struct Node
{
    Node *left, *right;
    int data;
     
    Node(int x)
    {
        data = x;
        left = NULL;
        right = NULL;
    }
};
 
// Function to calculate and return
// the Alpha Score of the journey
long getAlphaScore(Node* node)
{
     
    // Traverse left subtree
    if (node->left != NULL)
        getAlphaScore(node->left);
 
    // Calculate the alpha score
    // of the current step
    sum = (sum + node->data) % mod;
 
    // Update alpha score of
    // the journey
    total_sum = (total_sum + sum) % mod;
 
    // Traverse right subtree
    if (node->right != NULL)
        getAlphaScore(node->right);
 
    // Return
    return total_sum;
}
 
// Function to construct a BST
// from the sorted array arr[]
Node* constructBST(int arr[], int start,
                   int end, Node* root)
{
    if (start > end)
        return NULL;
 
    int mid = (start + end) / 2;
 
    // Insert root
    if (root == NULL)
        root = new Node(arr[mid]);
 
    // Construct left subtree
    root->left = constructBST(arr, start,
                              mid - 1, root->left);
 
    // Construct right subtree
    root->right = constructBST(arr, mid + 1, end,
                               root->right);
 
    // Return root
    return root;
}
 
// Driver Code
int main()
{
    int arr[] = { 10, 11, 12 };
    int length = 3;
     
    // Sort the array
    sort(arr, arr + length);
     
    Node *root = NULL;
     
    // Construct BST from the sorted array
    root = constructBST(arr, 0, length - 1, root);
     
    cout << (getAlphaScore(root));
}
 
// This code is contributed by mohit kumar 29

Java




// Java Program to implement
// the above approach
import java.lang.*;
import java.util.*;
 
// Structure of a node
class Node {
    Node left, right;
    int data;
    public Node(int data)
    {
        this.data = data;
        left = null;
        right = null;
    }
}
 
class AlphaScore {
 
    Node root;
 
    AlphaScore() { root = null; }
 
    static long sum = 0, total_sum = 0;
    static long mod = 1000000007;
 
    // Function to calculate and return
    // the Alpha Score of the journey
    public static long getAlphaScore(Node node)
    {
        // Traverse left subtree
        if (node.left != null)
            getAlphaScore(node.left);
 
        // Calculate the alpha score
        // of the current step
        sum = (sum + node.data) % mod;
 
        // Update alpha score of
        // the journey
        total_sum = (total_sum + sum) % mod;
 
        // Traverse right subtree
        if (node.right != null)
            getAlphaScore(node.right);
 
        // Return
        return total_sum;
    }
 
    // Function to construct a BST
    // from the sorted array arr[]
    public static Node constructBST(int[] arr, int start,
                                    int end, Node root)
    {
        if (start > end)
            return null;
 
        int mid = (start + end) / 2;
 
        // Insert root
        if (root == null)
            root = new Node(arr[mid]);
 
        // Construct left subtree
        root.left
            = constructBST(arr, start, mid - 1, root.left);
 
        // Construct right subtree
        root.right
            = constructBST(arr, mid + 1, end, root.right);
 
        // Return root
        return root;
    }
 
    // Driver Code
    public static void main(String args[])
    {
 
        int arr[] = { 10, 11, 12 };
        int length = arr.length;
 
        // Sort the array
        Arrays.sort(arr);
 
        Node root = null;
 
        // Construct BST from the sorted array
        root = constructBST(arr, 0, length - 1, root);
 
        System.out.println(getAlphaScore(root));
    }
}

Python3




# Python3 program to implement
# the above approach
 
# Structure of a node
class Node:
    def __init__(self, data):
         
        self.data = data
        self.left = None
        self.right = None
         
sum = 0
total_sum = 0
mod = 1000000007
     
# Function to calculate and return
# the Alpha Score of the journey
def getAlphaScore(node):
     
    global sum
    global total_sum
     
    # Traverse left subtree
    if node.left != None:
        getAlphaScore(node.left)
         
    # Calculate the alpha score
    # of the current step
    sum = (sum + node.data) % mod
     
    # Update alpha score of
    # the journey
    total_sum = (total_sum + sum) % mod
     
    # Traverse right subtree
    if node.right != None:
        getAlphaScore(node.right)
         
    # Return
    return total_sum
 
# Function to construct a BST
# from the sorted array arr[]
def constructBST(arr, start, end, root):
     
    if start > end:
        return None
     
    mid = (start + end) // 2
     
    # Insert root
    if root == None:
        root = Node(arr[mid])
         
    # Construct left subtree
    root.left = constructBST(arr, start,
                             mid - 1,
                             root.left)
     
    # Construct right subtree
    root.right = constructBST(arr, mid + 1,
                              end, root.right)
     
    # Return root
    return root
 
# Driver code
arr = [ 10, 11, 12 ]
length = len(arr)
 
# Sort the array
arr.sort()
 
root = None
 
# Construct BST from the sorted array
root = constructBST(arr, 0, length - 1, root)
 
print(getAlphaScore(root))
 
# This code is contributed by Shivam Singh

C#




// C# program to implement
// the above approach
using System;
 
// Structure of a node
class Node
{
    public Node left, right;
    public int data;
    public Node(int data)
    {
        this.data = data;
        left = null;
        right = null;
    }
}
 
class AlphaScore{
 
Node root;
 
AlphaScore(){root = null;}
 
static long sum = 0, total_sum = 0;
static long mod = 1000000007;
 
// Function to calculate and return
// the Alpha Score of the journey
static long getAlphaScore(Node node)
{
     
    // Traverse left subtree
    if (node.left != null)
        getAlphaScore(node.left);
 
    // Calculate the alpha score
    // of the current step
    sum = (sum + node.data) % mod;
 
    // Update alpha score of
    // the journey
    total_sum = (total_sum + sum) % mod;
 
    // Traverse right subtree
    if (node.right != null)
        getAlphaScore(node.right);
 
    // Return
    return total_sum;
}
 
// Function to construct a BST
// from the sorted array []arr
static Node constructBST(int[] arr, int start,
                         int end, Node root)
{
    if (start > end)
        return null;
 
    int mid = (start + end) / 2;
 
    // Insert root
    if (root == null)
        root = new Node(arr[mid]);
 
    // Construct left subtree
    root.left = constructBST(arr, start,
                             mid - 1, root.left);
 
    // Construct right subtree
    root.right = constructBST(arr, mid + 1,
                              end, root.right);
 
    // Return root
    return root;
}
 
// Driver Code
public static void Main(String []args)
{
 
    int []arr = { 10, 11, 12 };
    int length = arr.Length;
 
    // Sort the array
    Array.Sort(arr);
 
    Node root = null;
 
    // Construct BST from the sorted array
    root = constructBST(arr, 0, length - 1, root);
 
    Console.WriteLine(getAlphaScore(root));
}
}
 
// This is code contributed by PrinciRaj1992
Output: 
64





Time Complexity: O(NlogN) 
Auxiliary Space: O(N)
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :