↓Skip to main content
  1. LeetCode/

LeetCode 709: To Lower Case

·1 min· ·
LeetCode Easy String
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-31

  • Submissions: Internal Error → Runtime Error ×3 → Accepted ×2

Approach
#

'A' to 'Z' are 65 to 90 and lowercase is exactly 32 higher. Check each character and convert uppercase ones with chr(ord(c) + 32) (String Template 4). In practice it is s.lower().

My Attempts
#

The first three wrote ord(s) (the whole string) in the condition, a TypeError for any string longer than one character, and two also lacked a closing bracket. Attempt 4 tried ord(int(i)), a ValueError on letters. Going back to ord(i) passed.

Solution
#

class Solution:
    def toLowerCase(self, s: str) -> str:
        return "".join(chr(ord(c) + 32) if "A" <= c <= "Z" else c for c in s)

Complexity
#

Time O(n), space O(n).

Mistakes to Avoid
#

  • Call ord on a single character, not the whole string.

Interview Explanation
#

Uppercase letters become lowercase by adding 32 in ASCII, so I convert each character in A to Z and leave the rest. Time O(n).

Related

LeetCode 680: Valid Palindrome II
·2 mins
LeetCode Easy Two-Pointers String Greedy
LeetCode 680 note: at the first mismatch the only options are deleting the left or the right character; check whether either remainder is a palindrome
LeetCode 696: Count Binary Substrings
·2 mins
LeetCode Easy Two-Pointers String
LeetCode 696 note: split the string into runs of equal characters; each adjacent pair of runs contributes min(previous, current) substrings
LeetCode 599: Minimum Index Sum of Two Lists
·2 mins
LeetCode Easy Array Hash-Table String
LeetCode 599 note: map list1’s strings to indices, sum both indices while scanning list2, and keep every string with the minimum sum
LeetCode 551: Student Attendance Record I
·1 min
LeetCode Easy String
LeetCode 551 note: fewer than two A’s and no LLL substring
LeetCode 504: Base 7
·1 min
LeetCode Easy Math String
LeetCode 504 note: repeatedly take % 7 and // 7 of the absolute value, then add the sign and reverse; handle 0 separately
LeetCode 541: Reverse String II
·1 min
LeetCode Easy Two-Pointers String
LeetCode 541 note: in every block of 2k reverse the first k; when fewer than k remain reverse them all, which slicing handles automatically