50. Pow(x,n) – Solution

Difficulty: medium
Topics: math, recursion

Implement pow(x, n), which calculates x raised to the power n

Example 1:
Input: x = 2.00000, n = 10
Output: 1024.00000

Example 2:
Input: x = 2.10000, n = 3
Output: 9.26100

Example 3:
Input: x = 2.00000, n = -2
Output: 0.25000

Solution

O(n) approach would be just multiplying x n times:

Pow(x,n)=x*x*x\dotsm \Large

O(logn) approach is using an algorithm called “binary exponentiation“. This requires understanding that x^n can be decomposed in 2 ways:

if n is even:

x^{n} = {x}^{\frac{n}{2}}*{x}^{\frac{n}{2}} \Large

if n is odd:

x^{n} = x * x^{n-1} = x * {x}^{\frac{n-1}{2}} * {x}^{\frac{n-1}{2}} \Large

This can be handled recursively. x^n is decomposed into expressions with smaller ‘n’s until n becomes 0. When n becomes 0, we return 1.

class Solution {
public:
    double binaryExp(double x, long long n) {
        if (n == 0) return 1;
       
        // Handle case where, n < 0.
        if (n < 0) return 1.0 / binaryExp(x, -1 * n);
       
        // Perform Binary Exponentiation.
        double rec = binaryExp(x, n / 2);
        if (n % 2 == 1) return x * rec * rec;
        else return rec * rec;
    }

    double myPow(double x, int n) {
        return binaryExp(x, (long long) n);
    }
};

34. Find First and Last Position of Element in Sorted Array – Solution

Difficulty: medium
Topics: array, binary search

Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.

If target is not found in the array, return [-1, -1].

You must write an algorithm with O(log n) runtime complexity.

Example 1:
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]

Example 2:
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]

Example 3:
Input: nums = [], target = 0
Output: [-1,-1]

Leetcode problem 34

Solution

The way to handle this is by finding start and end pos separately.

We can do this by implementing separate binary searches to find lower bound and higher bound of target.

OR just make one binary search to find the lower bound of target and find the end position by finding the lower bound of (target+1).

The first approach is shown below:

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        // if it's empty,
        if (nums.size() == 0){
            vector<int> res = {-1, -1};
            return res;
        }
        
        // search left bound
        int l = 0, r = nums.size()-1;
        int leftrange = 0;
        while (l < r){
            int mid = (l+r)/2;
            if (nums[mid] >= target) r = mid;
            else l = mid+1;
        }
        if (nums[l] != target) leftrange = -1; 
        else leftrange = l; 

        // search right bound
        l = 0, r = nums.size()-1;
        int rightrange = 0;
        while (l < r){
            int mid = (l+r+1)/2;
            if (nums[mid] <= target) l = mid;
            else r = mid-1;
        }
        if (nums[l] != target) rightrange = -1;
        else rightrange = l; 
        
        // print the result
        vector<int> res = {leftrange, rightrange};
        return res;
    }
};

By only implementing binSearch that finds lower bound:

class Solution {
private:
    int lower_bound(vector<int>& nums, int low, int high, int target){
        while(low <= high){
            int mid = (low + high) >> 1;
            if(nums[mid] < target){
                low = mid + 1;
            }
            else{
                high = mid - 1;
            }
        }
        return low;
    }

public:
    vector<int> searchRange(vector<int>& nums, int target) {
        int low = 0, high = nums.size()-1;
        int startingPosition = lower_bound(nums, low, high, target);
        int endingPosition = lower_bound(nums, low, high, target + 1) - 1;
        if(startingPosition < nums.size() && nums[startingPosition] == target){
            return {startingPosition, endingPosition};
        }
        return {-1, -1};
    }
};

Since we already have a built in lower_bound library function, we can use that:

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        int startingPosition = lower_bound(nums.begin(), nums.end(), target) - nums.begin();
        int endingPosition = lower_bound(nums.begin(), nums.end(), target+1) - nums.begin() - 1;
        if(startingPosition < nums.size() && nums[startingPosition] == target){
            return {startingPosition, endingPosition};
        }
        return {-1, -1};
    }
};

As I begin this…

There is a question that doesn’t seem to leave my mind these days.

Have I ever passionately devoted my time on something, losing the track of time and surroundings? Have I ever experienced a graceful failure, one that I feel no remorse or sadness as I know I couldn’t have done it better?

Seeing some people who possess the ‘grit’ to become the best in their field, I am always amazed and ashamed at the same time.

I have explored diverse areas like game development in Unity, app development with Android Studio, TensorFlow, Web Development, etc. But my greatest regret is not specializing in one area and failing to learn a unique skill that sets me apart.

These days, I think I have finally decided what job to pursue after months of contemplation and wavering. I am interested in quantitative development and finance, fields that require an extraordinary level of talent and effort. I am also interested in Data Science and will probably do that if not quant.

For a job in quant, mathematical and problem solving skills are really important. Therefore, as of November 2023, I am starting to study DS and Algorithms with C++. I have never seen my limits as I have never put deadly effort into something. Therefore, I can’t even conclude if I am suitable or not for this kind of math heavy career (which makes me mad). I am in my 1st year 1st semester of college as I write this, and now the time has come. It’s okay to fail. Let’s see how far I can go with this.

“My math genius friend is having difficulty getting internships. Do you think you are going to quant?”

“My sister’s friend who graduated from Caltech is working in quant. and my sister says she is so talented”

Remember. Grit and Patience. and Never give up.