Single Element in a Sorted Array

Single Element in a Sorted Array. Find the element that appears once in a sorted array where every other element appears twice.

Given a sorted array of integers. In this array, every element appears twice except one element which appears only once. Write a code to find the element which appears only once.

For example:

Example 1:

Input: [1, 1, 2, 2, 3, 4, 4, 7, 7]

Output: 3

Except 3 every other element appears twice.

Example 2:

Input: [1, 1, 2, 2, 3, 3, 4, 5, 5]
Output: 4

NOTE – Try to solve this problem in O(logn) time complexity and by using constant space O(1).

Get Minimum Element From Stack in O(1)

Get minimum element from stack in O(1).

In this problem, we have to design a stack that supports push, pop, top, and retrieving the minimum element in constant time (O(1)).

      push(x) Push element x onto stack.

     pop() Removes the element on top of the stack.

     top() Get the top element.

     getMin() Retrieve the minimum element in the stack.

For example: Suppose, If we push the following elements in a stack.

9  ==> Top
1
2
3

Then if we call getMin() method, It should return 1 in O(1) (constant time).

How to Check if a Number is a Power of Two

How to check if a number is a power of two.  Give an integer, write a function to check if it is a power of two.

Example –

Input – 16   – 16 is a power of 2 (2^4).

Input – 15 – 15 is not a power of 2.

Input – 32- 32 is a power of 2 (2^5).

We can use multiple approaches to check whether a number is a power of 2 or not.