DEV Community

Pankaj Tanwar
Pankaj Tanwar

Posted on • Originally published at pankajtanwar.in

Challenge of the day #20 - To Lower Case.

Hey-yo people!

Welcome to yet another edition (day 20) of my coding diary. I am sure, you might be having some thoughts about what I do here. So, every day I solve a challenge, sharing some interesting approaches + my learning.

Well, let's jump straight to the problem statement for the day!


Problem of the day - To Lower Case

Tag - Easy

Given a string s, return the string after replacing every uppercase letter with the same lowercase letter.

Example 1:

Input: s = "Hello"
Output: "hello"


I don't even need to re-iterate the problem. It's the simple challenge one can ever get. Hold on, I know it can be solved within seconds but trust me, we are going to discuss some really cool insights.

I have a couple of solutions for this problem -

The very first, simplest solution

class Solution {
public:
    string toLowerCase(string s) {
        for(int i=0;i<s.length();i++) {
            s[i] = tolower(s[i]);
        }
        return s;
    }
};

Enter fullscreen mode Exit fullscreen mode

I am sorry, don't punish me for using the built-in function.

ASCII comes to rescue

class Solution {
public:
    string toLowerCase(string s) {
        for(int i=0;i<s.length();i++) {
            if(int(s[i]) >= 65 && int(s[i]) <= 90) s[i] += 32;
        }
        return s;
    }
};
Enter fullscreen mode Exit fullscreen mode

Pretty straightforward!

Tip for C++ beginners: Use int() to convert char to decimal and use char() to convert, a number to ASCII Char.

I usually, struggle to remember the exact ASCII code of A, Z,a,z. So, I did this -

class Solution {
public:
    string toLowerCase(string s) {
        for(int i=0;i<s.length();i++) {
            if(s[i] >= 'A' && s[i] <= 'Z') s[i] += 32;
        }
        return s;
    }
};
Enter fullscreen mode Exit fullscreen mode

Ahh, Some times I don't even remember the difference is 32. So,

if(s[i] >= 'A' && s[i] <= 'Z') s[i] = s[i] - 'A' + 'a';
Enter fullscreen mode Exit fullscreen mode

Here is the hilarious approach to optimize it further.

As, to optimize the comparison, instead of using -

if(s[i] >= 'A' && s[i] <= 'Z')
Enter fullscreen mode Exit fullscreen mode

we can do,

if(s[i] <= 'Z' && s[i] >= 'A')
Enter fullscreen mode Exit fullscreen mode

So, the thought is, for every lower case letter, it will get rejected in the first check itself, of the if condition. One comparison saved! (drum rolls please)

I know I am being too picky here but that's how I optimized it further. Not to mention, my runtime beats 100% of the submissions.

One guy solved it using bit manipulation. Insane!


You might like previous editions of my coding diary

Discussion (0)