Hey there people on the internet. Here's my solution for Paste 4 Linux shell challenge from HackerRank. You can find answers to other Linux shell challenges via this link => https://blog.shasec.rocks/post/hackerrank-bash-challs. So let's get started. 

Challenge

There are N  integers in an array A. All but one integer occur in pairs. Your task is to find the number that occurs only once.

> Input Format

The first line of the input contains an integer N, indicating the number of integers. The next line contains N space-separated integers that form the array A.

> Constraints

1 <= N <= 100

N % 2 = 1 (N is an odd number)

> Output Format

Output S, the number that occurs only once.

> Sample Input 1

1
1

> Sample Output 1

1

> Sample Input 2

3
1 1 2

> Sample Output 2

2

> Sample Input 3

5
0 0 1 2 1

> Sample Output 3

2

> Explanation

In the first input, we see only one element (1) and that element is the answer.

In the second input, we see three elements; 1 occurs at two places and 2 only once. Thus, the answer is 2.

In the third input, we see five elements. 1 and 0 occur twice. The element that occurs only once is 2.

Solution

#/bin/bash

# Create empty Array
arr=()

# Variable to track the index of the array
count=0

# Get user input including the last line of input
while read line || [ -n "$line" ]; do

    # Skip the first input. I only want the space separated numbers
    if(( $count <= 0 )); then
        count=$(( $count+1 ))
        continue
    fi

    # Append to array
    arr[$count]=$line

    # Increment the count index
    count=$(( $count+1 ))

done

# Get only the uniq number/s
echo $(echo -e "${arr[@]}" | tr ' ' '\n' | sort | uniq -u)
Blog Image
Figure 1.0: Solution passed all HackerRank tests cases

If you like content like this, please consider buying me a coffee.

Thank you for your support :)


👇 Share this post 👇


💬 Comment Section 💬