Remove Duplicates From Sorted Array

Given a sorted array, we have to write a code to remove the duplicates in-place such that each element appear only once and return the new length.

For this problem, we don’t have to use extra space. As we have to remove duplicates in-place (In O(1)).

Note that we have to return the new length, make sure to change the original array as well in place

For example:

Input : { 1, 2, 2, 3, 4, 4, 5, 6, 6, 7 }

Output: 7

Our function should return length 7 with first seven elements of array are {1, 2, 3, 4, 5, 6, 7}. It doesn’t matter what you leave beyond the returned length

Subarray with Given Sum

Find subarray with given sum.

Given an array of unsorted integers (Positive integers), We have to write a code to find a subarray whose sum is equal to a given sum.

We have to return subarray indexes (start and end index).

For Example –

  Example 1 :

Input : arr = {10, 2, 4, 7, 5}, sum = 13

Output: {1, 3}

The numbers present from the 1st to 3rd indexes are 2, 4, 7. When we add (2 + 4 + 7) it is 13.

Example 2 :

Input : arr = {1, 4, 20, 3, 10, 5}, sum = 33

  Output: {2, 4}

Example 3 :

  Input : arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, sum = 15

   Output: {0, 4}

Happy Number

In this tutorial, I am going to discuss a very interesting problem to determine if a number is happy or not.

Given a number n, we have to write a code to check whether a number is happy or not.

Happy Number

Take any positive integer, and replace the number with the sum of the squares of its digits. Repeat the process until the number equals 1 (where it will stay). If it’s equal to 1 then it’s a happy number. If it loops endlessly in a cycle which does not include 1 then it’s not a happy number.

Those numbers for which this process ends in 1 are happy numbers.

For Example –

Example 1:

Input : 19, Output: true

Step 1: 1^2 + 9^2 = 82

Step 2: 8^2 + 2^2 = 68

Step 3: 6^2 + 8^2 = 100

Step 4: 1^2 + 0^2 + 0^2 = 1 (The number ends at 1, So it’s a happy number).

Example 2:

Input  :  20, Output :  false

Step 1: 2^2 + 0^2 = 4

Step 2: 4^2  = 16

Step 3: 1^2 + 6^2 = 37

Step 4: 3^2 + 7^2 = 58

Step 5: 5^2 + 8^2 = 89

Step 6: 8^2 + 9^2 = 145

Step 7: 1^2 + 4^2 + 5^2 = 42

Step 8: 4^2 + 2^2 = 20 (Loop occurs)