Convert Binary Linked List to Integer.

Given a Singly Linked List containing n nodes, each node of the list can hold either 0 or 1 and the most significant bit is present at the head of the linked list. The entire linked list is a binary representation of a decimal number. Return the decimal value represented by the given binary linked list. 


Note: The linked list is not empty and the maximum number of nodes will be less than 30.

Convert Binary Linked List to Integer.

Example 1: 
Input: 1->0->1->1
Output: 11

Example 2:
Input: 1->0->1
Output: 5

Approach 1: Converting Binary Using Arithmetic calculation.

You can solve this problem by diving the problem into two sub-problems:
  • Find the number of binary digits present in the given linked list that is needed for the arithmetic calculation.
  • Convert the Binary to a Decimal number using classic arithmetic calculation (see the above image).
C++ Solution Code:

//C++ Program to convert Binary Linked List to Decimal
#include<bits/stdc++.h>
using namespace std;

class ListNode{
    public:
      int data;
      ListNode *next;

    //constructor
    ListNode(int data){
        this->data = data;
        this->next = NULL;
    }  
};
//creating new node
ListNode *newNode(int data){
    ListNode *temp = new ListNode(data);
    temp->next = NULL;
    return temp;
}
//function to find length of linked list
int listLength(ListNode* head){
    ListNode *temp = head;
    int len = 0;
    while(temp != NULL){
        temp = temp->next;
        len++;
    }
    return len;
}
//function to convert binary to decimal
int getDecimalValue(ListNode *head){
    
    int len = listLength(head);
    int ans = 0;
    ListNode *temp = head;
    int i = 1;

    while(temp != NULL){
        int res = (temp->data)*pow(2, len-i);
        temp = temp->next;
        i++;
        ans += res;
    }
    return ans;
}
int main(){
    ListNode *head = newNode(1);
    head->next = newNode(0);
    head->next->next = newNode(1);

    cout<<"Integer Value: "<<getDecimalValue(head);

    return 0;
}
Output:
Integer Value: 5
  • Time Complexity: O(n)
  • Space Complexity: O(1)

Approach 2:
Using Bit Manipulation.

In this approach, bit manipulation technique in which we will traverse the linked list starting from head till end. Updating the current value with head->next->value. Updating the result by shifting the digit by one to the left and performing logical OR with current vlaue.

C++ Solution code:
/*C++ Program to convert Binary Linked List to Decimal
Using bit manipulation*/
#include<bits/stdc++.h>
using namespace std;

class ListNode{
    public:
      int data;
      ListNode *next;

    //constructor
    ListNode(int data){
        this->data = data;
        this->next = NULL;
    }  
};
//creating new node
ListNode *newNode(int data){
    ListNode *temp = new ListNode(data);
    temp->next = NULL;
    return temp;
}

//function to convert binary to decimal
int getDecimalValue(ListNode *head){
    
    int num = head->data;
    while (head->next != NULL)
    {
        num = (num << 1) | head->next->data;
        head = head->next;
    }
    
    return num;
}
int main(){
    ListNode *head = newNode(1);
    head->next = newNode(0);
    head->next->next = newNode(1);

    cout<<"Integer Value: "<<getDecimalValue(head);

    return 0;
}
Output:
Integer Value: 5
  • Time Complexity: O(n)
  • Space Complexity: O(1)

Related Articles:

Program to Find Sum of All Odd Length Subarrays.

Given a positive integer array num of size n, calculate and return the sum of all possible odd-length subarrays of num.

Example:
Example 1:
Input: num[] = {1, 3, 2, 5, 6};
Output: 63

Explanation: 
List of Odd length subarrays:
[1] = 1
[3] = 3
[2] = 2
[5] = 5
[6] = 6
[1, 3, 2] = 6
[3, 2, 5] = 10
[2, 5, 6] = 13
[1, 3, 2, 5, 6] = 17
Sum of all odd length arrays: 1+3+2+5+6+6+10+13+17 = 63

Example 2:
Input: num[] = {3, 5}
Output: 8

Explanation:
List of Odd length subarrays:
[3] = 3
[5] = 5
Sum of all odd length arrays: 3+5 = 8

Approach 1: Brute Force Solution.

You can quickly get all possible subarrays by running two nested loops but the critical point of this problem is that you need to find only all odd-length subarrays. 

odd length subarray formula

You can use a generalized formula that if [(last_position_of_subarray - first_positon_ of _subarray)%2 == 0] then the length is odd else the length is even. You can then add the elements of that subarray to your answer.


C++ Solution Code:

/*C++ code to find sum of odd length subarray*/
#include<bits/stdc++.h>
using namespace std;

int sumOfOddSubarray(vector<int> &num){
    int total = 0;

    for(int i = 0; i < num.size(); i++){
        int sum = 0;
        for(int j = i; j < num.size(); j++){
            sum += num[j];
            if((j - i)%2 == 0)
              total += sum;
        }
    }
    return total;
}

int main(){
    vector<int> num = {1, 3, 2, 5, 6};

    int ans = sumOfOddSubarray(num);
    cout<<"Sum Of Odd Length subarrays: "<<ans;

    return 0;   
}
Output:
Sum Of Odd Length subarrays: 63
  • Time Complexity: O(n^2)
  • Space Complexity: O(1)


Approach 2: Using Math.

In the previous approach, you check for all possible subarrays but in this approach, you are going to derive a mathematical formula to solve this problem in O(n) time complexity. This solution might be a little confusing but if you don't give up I am sure you will understand it well. Let's start,

If you observe the question carefully you will find that we only need the sum of subarrays we don't need to print them anywhere so if somehow you count the number of occurrences of each element in all possible odd-length subarray then you can multiply each element with their number of occurrences and sum them up together then you can get your required answer. Let's understand with one example.
In this above example image, we have taken only all odd-length subarrays 
Given: [1, 4, 2, 5, 3]

Element      Number of occurance      Sum
ar[0] = 1        3                    1x3 = 3
ar[1] = 4        4                    4x4 = 16
ar[2] = 2        5                    2x5 = 10
ar[3] = 5        4                    5x4 = 20
ar[4] = 3        3                    3x3 = 9
                                    Total = 58
Explanation: 
arr[2] = 2 present in 5 times(one time in row first, 
three times in row second and one time in row third)
similarly we need to count for all elements.

To create a subarray that contains arr[i]  we can take 0, 1, 2, ..... i element on the left hand side from arr[0] to  arr[i] and you get (i+1) choices to include arr[i] in the subarray. Similarly, you can take 0, 1, 2, ...... n-1-i element on the right-hand side from arr[i] to arr[n-1]. and you will get (n-i) choices to include arr[i] in the subarray.

In total you will get [k = (i+1)*(n-i)] number of subarrays that contains arr[i] so,
There is (k+1)/2 subarray with the odd length that contains arr[i].
There is (k/2) subarray with even length that contains arr[i].

We can derive a general formula with all the above observations and calculations for finding the number of times an element is occurring for odd-length subarrays.
n = ((i+1)*(n-i)+1)/2

C++ Solution Code:
/*C++ code to find sum of odd length subarray (Optimized)*/
#include<bits/stdc++.h>
using namespace std;

int sumOfOddSubarray(vector<int> &num){
    int total = 0;
    int n = num.size();

    for(int i = 0; i < n; i++){
        total += ((i+1)*(n-i)+1)/2 * num[i];
    }
    return total;
}

int main(){
    vector<int> num = {1, 4, 2, 5, 3};

    int ans = sumOfOddSubarray(num);
    cout<<"Sum Of Odd Length subarrays: "<<ans;

    return 0;   
}
Output:
Sum Of Odd Length subarrays: 58
  • Time Complexity: O(n)
  • Space Complexity: O(1)

Program to Count Number of Good Pair.

Given an integer array num of size n, return the count of possible good pairs. A pair of elements is called a good pair if (num[i] == num[j]) and i < j.

Example:
Example 1:
Input: num[] = {2, 1, 3, 2, 2, 3};
Output: 4

Explanation: 
There are four good pairs (0, 3), (0, 4), (2, 5) and (3, 4)

Example 2:
Input: num[] = {3, 3, 3, 3}
Output: 6

Approach 1: Brute Force Solution.

Take a count variable and initialize it with 0. Run two nested for loops for each element of the array, pick each element one by one and then compare it with the remaining element and then keep on increasing the count variable whenever the given condition is satisfied. 

C++ Solution Code:
/*C++ code for count number of good pairs*/
#include<bits/stdc++.h>
using namespace std;

int goodPairs(vector<int> &num){
    int count = 0;

    for(int i = 0; i < num.size(); i++){
        for(int j = i+1; j < num.size(); j++){
            if(num[i] == num[j])
              count++;
        }
    }
    return count;
}

int main(){
    vector<int> num = {2, 1, 3, 2, 2, 3};

    int count = goodPairs(num);
    cout<<"Number of Good Pairs: "<<count;

    return 0;   
}
Output:
Number of Good Pairs: 4
  • Time Complexity: Running two nested loops for n elements takes O(n^2) time complexity.
  • Space Complexity: No extra space is required in the above solution so space complexity is O(1).


Approach 2: Using Hash Map.

You can optimize the previous solution by using a hash map to get the count of each unique element of the array. 
Given num = [2, 1, 3, 2, 2, 3]

Structure of map:
Key      Value(count)
 2          3 (Value 2 appears 3 times)
 1          1 (Value 1 appears 1 times)
 3          2 (Value 3 appears 2 times)       

When you have n number of similar values then it can create [n*(n-1)/2] number of unique good pairs. 
[3, 3, 3, 3]
Number of Good Pairs = 4*(4-1)/2 = 6

Similarly, you can calculate the number of unique good pairs for each value of the map and sum them up to get the total number of good pairs possible from all array elements.
Key      Value(count)      Good Pairs
 2          3            [3*(3-1)/2 = 3] 
 1          1            [1*(1-1)/2 = 0]
 3          2            [2*(2-1)/2 = 1]  
Total number of Good Pairs = 3+0+1 = 4     

C++ Solution Code:
/*C++ code for count number of good pairs(Optimized)*/
#include<bits/stdc++.h>
using namespace std;

int goodPairs(vector<int> &num){
    int count = 0;
    unordered_map<int, int> mp;

    //Storing count of each unique element
    for(int i = 0; i < num.size(); i++){
        mp[num[i]]++;
    }

    //counting good pairs
    for(auto i:mp){
        int n = i.second;
        count += (n*(n-1))/2;
    }
    return count;
}

int main(){
    vector<int> num = {2, 1, 3, 2, 2, 3};

    int count = goodPairs(num);
    cout<<"Number of Good Pairs: "<<count;

    return 0;   
}
Output:
Number of Good Pairs: 4
  • Time Complexity: We run two separate loops one for storing the count in the map and the next loop for counting good pairs so the average time complexity will be O(n).
  • Space Complexity: We are using one map to store the count of elements so space complexity will be O(n).
Next:

Count number of elements smaller than current number.

Given an array num of size n, for each element of num count the number of elements of the array that are smaller than the current element. It means for each element num[i] you need to count the number of elements such that num[j] < num[i] and j != i. Return the counts in an array.

Example:
Example 1:
Input: num[] = {3, 2, 5, 1, 7};
Output: {2, 1, 3, 0, 4}

Explanation: 
Number of Elements smaller than num[0] = 3 are (1 and 2) = 2 
Number of Elements smaller than num[1] = 2 are (1) = 1
Number of Elements smaller than num[2] = 5 are (1, 2 and 3) = 3
Number of Elements smaller than num[3] = 1 are () = 0
Number of Elements smaller than num[4] = 7 are (1, 2, 3 and 5) = 4

Example 2:
Input: num[] = {3, 3, 3, 3}
Output: {0, 0, 0, 0}

Example 3:
Input: num[] = {3, 2, 2, 5, 1, 7}
Output: {3, 1, 1, 4, 0, 5}

The question is very simple, you just have to get the counts of smaller elements for each and store them one by one in an array or vector and return them as your output. This question can be solved by multiple approaches let's discuss them here.
Note: We are using a C++ vector in our solution instead of an array because vectors are dynamic in nature and provide more functionality. (alert-passed)  

Approach 1: Brute Force Solution.

You can run two nested loops, the outer loop will pick elements of the array one by one, and the inner loop will traverse the whole array each time to check and count the elements that satisfy the given condition. Each time the inner loop terminates store the count value into a new resulting array and return this array at the end. 
 
C++ Solution code:
/*C++ program for how many number of elements smaller
 than current number.*/
#include<iostream>
#include<vector>
using namespace std;

vector<int> smallerNumber(vector<int> &num){
    vector<int> ans;
    int count;

    for(int i = 0; i < num.size(); i++){
        count = 0;
        for(int j = 0; j < num.size(); j++){
            if(num[i] > num[j])
               count++;
        }
        ans.push_back(count);
    }
    return ans;
}

int main(){
    vector<int> num = {3, 2, 2, 5, 1, 7};
    vector<int> result = smallerNumber(num);

    for(int i = 0; i < result.size(); i++)
       cout<<result[i]<<" ";

    return 0;   
}
Output:
3 1 1 4 0 5
  • Time Complexity: Running two nested loops from 0 to n will take n x n units of time so the time complexity will be O(n^2).
  • Space Complexity: No extra space is required to perform any operation except the answer vector that is used to store the counts but we cannot consider this for calculating space complexity so overall space complexity will be O(1).


Approach 2: Using Hash Map and Sorting.

The above approach is solving the problem in O(n^2) time complexity but we can optimize the solution and can bring it to O(nlogn) time complexity by following the below algorithm.
Given num = [3, 2, 2, 5, 1, 7]

Step 1: Make a copy of the given array and sort it in ascending order.
copy = [1, 2, 2, 3, 5, 7]

Step 2: Store the values in a hash map corresponding to their index in reverse order. A map can store only unique values and storing values in reverse will help you to get the count of smaller values by their index.
mp[copy[5]] = mp[7] = 5
mp[copy[4]] = mp[5] = 4
mp[copy[3]] = mp[3] = 3
mp[copy[2]] = mp[2] = 1(overwritten 2 to 1)  
mp[copy[0]] = mp[1] = 0

Step 3: Store the values back in the num array.
num[0] = mp[num[0]] = mp[3] = 3
num[1] = mp[num[1]] = mp[2] = 1
num[2] = mp[num[2]] = mp[2] = 1
num[3] = mp[num[3]] = mp[5] = 4
num[4] = mp[num[4]] = mp[1] = 0
num[5] = mp[num[5]] = mp[7] = 5

Step 4: Return the num array as our answer.
num = [3, 1, 1, 4, 0, 5]

C++ Solution code:
/*C++ Optimized program for how many number of elements 
smaller than current number.*/
#include<bits/stdc++.h>
using namespace std;

vector<int> smallerNumber(vector<int> &num){
    unordered_map<int, int> mp;

    //make a copy vector
    vector<int> copy = num;
    //sort the copy vector in ascending order
    sort(copy.begin(), copy.end());

    //store elements corresponding to their index
    for(int i = num.size() - 1; i >= 0; i--){
        mp[copy[i]] = i;
    }
    
    //store map value back to num array
    for(int i = 0; i < num.size(); i++){
        num[i] = mp[num[i]];
    }
    return num;
}

int main(){
    vector<int> num = {3, 2, 2, 5, 1, 7};

    vector<int> result = smallerNumber(num);

    for(int i = 0; i < result.size(); i++)
       cout<<result[i]<<" ";

    return 0;   
}
Output:
3 1 1 4 0 5
  • Time Complexity: Sorting the copied array will take O(nlogn) time, and running two separate loops for n elements will take 2O(n) time so the overall time complexity of our solution is O(nlogn).
  • Space Complexity: As we are using a new copy vector and unordered map for storing the element so overall space complexity is O(n). 

How To Pass Array to Function in C++.

As we know that an array is a collection same kind of data in a contiguous memory location but can we pass the array data as an argument to a function? The answer to this question is no. We cannot pass the entire array as an argument to a function but we can pass a pointer to an array. 


We have totally different methods for passing a one-dimensional and two-dimensional array to a function in C++. Let's discuss both of them one by one:


Passing One-Dimensional Array to Function.

We have passed the name of our array without an index to a function and the name of the array behaves like a pointer folding the address of the first element of the array. Any changes made in the array inside the function will directly affect the elements of the main array. 

C++ Example Code:
//C++ Example to show ways of Passing Array to Function
#include<iostream>
using namespace std;

//Formal parameter as unsized array
void funType1(int arr[], int n){ int size = sizeof(arr)/sizeof(arr[0]); cout<<"\nSize of array inside fun1: "<<size<<endl; arr[2] = 10; cout<<"Array Elements in fun1: "; for(int i = 0; i < n; i++) cout<<arr[i]<<" "; }
//Formal parameter as a pointer
void funType2(int *arr, int n){ int size = sizeof(arr)/sizeof(arr[0]); cout<<"Size of array inside fun2: "<<size<<endl; arr[n-1] = 23; cout<<"Array Elements in fun2: "; for(int i = 0; i < n; i++) cout<<arr[i]<<" "; } int main(){ int arr[] = {3, 4, 5, 7, 8, 9}; //size of array int n = sizeof(arr)/sizeof(arr[0]); cout<<"Size of given array: "<<n<<endl; cout<<"Array Elements: "; for(int i = 0; i < n; i++) cout<<arr[i]<<" ";
        
        //function 1 call
funType1(arr, n); cout<<endl;
        //function 2 call
funType2(arr, n); return 0; }
Output:
Size of given array: 6
Array Elements: 3 4 5 7 8 9
Size of array inside fun1: 2
Array Elements in fun1: 3 4 10 7 8 9
Size of array inside fun2: 2
Array Elements in fun2: 3 4 10 7 8 23

We have two ways of writing an array into a function as an argument, 
  • The first is passing an unsized array as a parameter. (syntax: fun(int arr[])) 
  • The second is passing as a pointer. (syntax: fun(int *arr))
Both hold the address of only the first element of the array.
We cannot calculate the size of the array inside the function we must have to pass the array size as a parameter. 

Passing Two-Dimensional Array to Function.

To pass a 2D array (also known as a matrix) to a function we must have to pass the second dimension value to the function were passing the first dimension value is totally optional. 

Syntax: fun(int arr[][m])

C++ Example Code:
//C++ Example code for passing 2D array to function
#include<iostream>
using namespace std;

//Passing matrix to a function
void fun2DArray(int arr[][3], int r, int c){
	cout<<"Elements of 2D Array: "<<endl;
	for(int i = 0; i < r; i++){
		for(int j = 0; j < c; j++){
			cout<<arr[i][j]<<" ";
		}
		cout<<endl;
	}
}
int main(){
	
	int arr[][3] = {{2, 3, 7},{9, 5, 1},{4, 6, 2}};
	
	int row = sizeof(arr)/sizeof(arr[0]);
	int col = sizeof(arr[0])/sizeof(arr[0][0]);

	fun2DArray(arr, row, col);

	return 0;
}
Output:
Elements of 2D Array: 
2 3 7
9 5 1
4 6 2

In the above code, you can also check how we can calculate the number of rows and columns of a 2D Array using the sizeof() operator.

Next:

DON'T MISS

Tech News
© all rights reserved
made with by AlgoLesson