Friday, 30 April 2021

Count of Smaller Numbers After Self

import java.util.ArrayList;

import java.util.Collections;

import java.util.List;


/*https://www.youtube.com/watch?v=buDoT9ESw1c

*You are given an integer array nums and you have to return a new counts array. The counts array has the property

where counts[i] is the number of smaller elements to the right of nums[i].

Example:

Input: [5,2,6,1] Output: [2,1,1,0]

* */

public class CountOfSmallerNumbersAfterSelf {

    public static void main(String[] args) {

        int[] arr  ={7,5,2,6,1};

        Node root = new Node(arr[arr.length-1]);

        List<Integer> resultList = new ArrayList<>();

        resultList.add(0);

        for(int i=arr.length-2;i>=0;i--){

            resultList.add(insertNode(root,arr[i]));

        }

        Collections.reverse(resultList);

        System.out.println(resultList);



    }


    static int insertNode(Node root, int value){

        int result = 0;

        boolean isConnected = false;

        while (!isConnected){

            if(value<=root.value){

                //apend in left

                root.count++;

                if(root.left==null){

                    Node newNode = new Node(value);

                    root.left = newNode;

                    isConnected = true;

                }else{

                    root = root.left;

                }

            }else{

              //  append in right

                result = result+root.count;

                if(root.right==null){

                    Node newNode = new Node(value);

                    root.right = newNode;

                    isConnected = true;

                }else{

                    root = root.right;

                }

            }

        }


        return result;

    }




}


class Node{

    Node left;

    Node right;

    int value;

    int count=1;

    public Node(int value){

        this.value = value;

    }

}


No comments:

Post a Comment

links for Data Structure

  1) 𝐁𝐞𝐜𝐨𝐦𝐞 𝐌𝐚𝐬𝐭𝐞𝐫 𝐢𝐧 𝐋𝐢𝐧𝐤𝐞𝐝 𝐋𝐢𝐬𝐭:  https://lnkd.in/gXQux4zj 2) 𝐀𝐥𝐥 𝐭𝐲𝐩𝐞𝐬 𝐨𝐟 𝐓𝐫𝐞𝐞 𝐓𝐫𝐚𝐯𝐞𝐫𝐬𝐚𝐥𝐬...