# Coding Challenges

### 1. Sum Of Array Numbers (E)&#x20;

#### You are given an array of two numbers \[a,b]. Find the sum of those two numbers plus the sum of all the numbers between them.

> **Test Cases**

> sum(\[1, 4]) - Returns 10
>
> sum(\[4, 1]) - Returns 10
>
> **Solution**

{% tabs %}
{% tab title="SumOfArrayNumbers.js" %}

```javascript
// My Solution

const arr = [4, 1];

const sortedArr = arr.sort(); //sorts in asc order 

let temp = 0;

for (let i = sortedArr[0]; i <= sortedArr[sortedArr.length - 1]; i++) {
  temp += i;
}

console.log(temp);
```

{% endtab %}
{% endtabs %}

### 2. Factorial Of Numbers (E)&#x20;

#### Give an integer (num), find the factorial of that integer.&#x20;

> **Test Cases**
>
> factorial(0) - Returns 1 (We're not going to understand the math behind this)
>
> factorial(1) - Returns 1
>
> factorial(4) - Returns 24
>
> factorial(5) - Returns 120

{% tabs %}
{% tab title="Factorial.js" %}

```javascript
// My Solution

function factorial(num) {
	
	// 2 ->  2 * fact(1)
	// 3 ->  3 * fact(2)

	if (num === 1 || num === 0) {
		return 1;
	}

	return num * factorial(num - 1);
}


console.log(factorial(5));
```

{% endtab %}
{% endtabs %}

### 3. Fibonacci Sequence (E)&#x20;

#### Give a number n, find the first n elements of the Fibonacci series.

> **Fibonacci Series** is a series of numbers in which each number ( Fibonacci number ) is the sum of the two preceding numbers.
>
> **Test Cases**
>
> printFibonacci(2) - Returns 0 1
>
> printFibonacci(7) - Returns 0 1 1 2 3 5 8

{% tabs %}
{% tab title="Fibonacci.js" %}

```javascript
// My Solution

function fibonacci (n) {
  if (n < 2) {
    return n
  }
  return fibonacci(n - 1) + fibonacci(n - 2)
}

function printFibonacci (n) {
  for (let i = 0; i < n; i++) {
    console.log(fibonacci(i))
  }
}

printFibonacci(7)
```

{% endtab %}
{% endtabs %}

### 4. Find Prime Numbers (M)&#x20;

#### Given two numbers min and max, find all the prime numbers in the range of min to max. (min and max included)

> **Test Cases**
>
> printPrime(0, 20) - Returns 2 3 5 7 11 13 17 18

{% tabs %}
{% tab title="PrimeNumbersTwoForLoops.js" %}

```javascript
// My Solution

function printPrime (min, max) {

   const primeNums = []
	
	// starts from min and checks until max
	for(let num = min; num<=max; num++){
	
	  let isPrime = true
	  
	  // check is used to divide num
	  for(let check = 2; check <= num/2; check++){
	    
		   if(num%check === 0){
			   isPrime = false
			}

	  }
	  
	  if(isPrime && num !==0 && num !==1 ){
	    primeNums.push(num);
	  }
	  
	
	}
	
	return primeNums

}


console.log(printPrime(0,2))
```

{% endtab %}

{% tab title="PrimeNumbersTwoFunctions.js" %}

```javascript
// Codevolution Solution - https://learn.codevolution.dev/courses/1222162/lectures/27379570

function isPrime (n) {

  let primeFlag = true
  
  // Sufficient to check till n/2
  
  for (let i = 2; i <= n / 2; i++) {
  
    // if n is divisible by any number then it is not prime
    
    if (n % i === 0) {
      primeFlag = false
      break
    }
  }
  
  if (primeFlag) {
    console.log(n)
  }
}

function printPrime (min, max) {
  for (let i = min; i <= max; i++) {
    // Skip 0 and 1
    if (i === 0 || i === 1) {
      continue
    }
    isPrime(i)
  }
}

printPrime(0, 20)
```

{% endtab %}
{% endtabs %}

### 5. Is Palindrome (E)

#### Given a string (str), determine if it is a palindrome. A palindrome is a word, phrase, or sequence that reads the same backward as forwards, e.g. madam.

{% tabs %}
{% tab title="isPalindrome.js" %}

```javascript
// My Solution

const str = 'racecar';     // true
/* const str = 'car'; */   // false

function checkPal(str){

  let reverse = '';
  for(let i=str.length-1; i>=0; i--) {
  
    reverse += str[i]
    
  }

  if(str == reverse) 
  
    return true
   return false 
   
}

console.log(checkPal(str))

```

{% endtab %}

{% tab title="isPalindromeUsingRevers.js" %}

```javascript
// Codevolution Solution - https://learn.codevolution.dev/courses/1222162/lectures/27379740

function isPalindrome (str) {

  return (
    str.toLowerCase() ===
    str
      .toLowerCase()
      .split('')
      .reverse()
      .join('')
  )
  
}

console.log(isPalindrome('racecar'))

```

{% endtab %}
{% endtabs %}

### 6. Is Anagram (M)

#### Given two strings (str1 and str2), determine if str1 is an anagram of str2. An Anagram is a word, phrase, or name formed by rearranging the letters of another, such as `spar`, formed from `rasp`.

{% tabs %}
{% tab title="isAnagram.js" %}

```javascript
// My Solution

function anagram(wordOne, wordTwo) {
  // sort both the words and then compare

  // can validate if both the params are string here before sorting

  const sortedOne = wordOne.split("").sort().join("");
  const sortedTwo = wordTwo.split("").sort().join("");

  return sortedOne.toLowerCase() === sortedTwo.toLowerCase();
}

console.log(anagram("maAm", "amma")); // true
console.log(anagram("mamm", "amma")); // false
```

{% endtab %}
{% endtabs %}

### 7. Reverse Words (E)

#### Given an input string (str), reverse the string word by word.

{% tabs %}
{% tab title="reverseWords.js" %}

```javascript
// My Solution

function wordReverse(str) {
  // str -> Hello World

  const wordArr = str.split(" "); // Hello World -> [Hello World]
  
  let reverseWord = "";
  console.log(wordArr.length)

  for (let i = wordArr.length - 1; i >= 0; i--) {
    reverseWord += wordArr[i] + " ";
  }

  return reverseWord;
}

console.log(wordReverse("Hello World"));

```

{% endtab %}

{% tab title="reverseWords.js" %}

```javascript
// Codevolution Solution - https://learn.codevolution.dev/courses/1222162/lectures/27380082

// LOGIC - Split the string into array and then use reverse keyword and then join the array

function wordReverse(str) {
  // str -> Hello World

 return str.trim().split(" ").reverse().join(" ")

}

console.log(wordReverse("Hello World"));

```

{% endtab %}
{% endtabs %}

### 8. Unique element/s in the array (M)

#### Find first occurred unique element/s in array

{% tabs %}
{% tab title="firstUniqueElement.js" %}

```javascript
// Print the first unique element of Array

const arr = [1, 1, 2, 5, 4, 3, 3, 2]; // 5 is the first unique element

for (let i = 0; i < arr.length; i++) {
    let count = 0;
    for (j = 0; j < arr.length; j++) {
        if (arr[i] === arr[j]) {
            count++;
        }
        if (count > 1) {
            break
        }
    }

    if (count == 1) {
        console.log(`The first unique element is ${arr[i]}`)
        return;
    }
}

```

{% endtab %}

{% tab title="findUniqueElementFunction.js" %}

```javascript
// Print the first unique element of Array

// const arr = [1, 1, 2, 5, 3, 3, 2]; // 5 is the first unique element
const arr = [1, 1, 2, 3, 3, 2]; // no unique elements


function findUniqueElement(arr) {
    for (let i = 0; i < arr.length; i++) {
        let count = 0;
        for (j = 0; j < arr.length; j++) {
            if (arr[i] === arr[j]) {
                count++;
            }
            if (count > 1) {
                break
            }
        }

        if (count == 1) {
            console.log(`The first unique element is ${arr[i]}`)
            return;
        }
    }
    console.log("No unique elements found")
}

findUniqueElement(arr);
```

{% endtab %}

{% tab title="allUniqueElements.js" %}

```javascript
// Return all the unique element of Array

const arr = [1, 1, 2, 5, 3, 3, 2, 8] // 5 and 8 is the first unique element
// const arr = [1, 1, 2, 3, 3, 2] // no unique elements
const uniqueArray = []
function findUniqueElements(arr) {
    for (let i = 0; i < arr.length; i++) {
        let count = 0
        for (j = 0; j < arr.length; j++) {
            if (arr[i] === arr[j]) {
                count++
            }
            if (count > 1) {
                break
            }
        }

        if (count == 1) {
            uniqueArray.push(arr[i])
        }
    }
    return uniqueArray
}

console.log(findUniqueElements(arr))
```

{% endtab %}
{% endtabs %}

### 10. Remove Vowels from String (E)

#### Remove 'a','e','i','o',u'

{% tabs %}
{% tab title="splitJoinMethod.js" %}

```javascript

// vowels - a, e, i, o, u
const str = "vishwas"

const consonents = str
    .split("")
    .filter(letter => !(letter === "a" || letter === "e" || letter === "i" || letter === "o" || letter === "u"))
    .join("")

console.log(consonents)
```

{% endtab %}

{% tab title="replaceRegexMethod.js" %}

```javascript

function removeVowels (str) {
  // g - global, i - case insensitive
  return str.replace(/[aeiou]/gi, '')
}

console.log(removeVowels('Hello World'))
```

{% endtab %}
{% endtabs %}

### 11. Reverse Words (E)

{% tabs %}
{% tab title="reverseWords.js" %}

```javascript
// reverse words

function reverseWords(words) {

    const wordsArray = words.split(" ").reverse().join(" ")
    console.log(wordsArray)

}

reverseWords("Hello World") // World Hello
```

{% endtab %}
{% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://sandeepamaranath.gitbook.io/notes/interview/technical/interview-coding-challenges.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
