Press "Enter" to skip to content

Posts tagged as “reverse”

花花酱 LeetCode 7. Reverse Integer


Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Solution: Simulation

Reverse digit by digit. Be careful about the overflow and negative numbers (especially in Python)

Time complexity: O(log(x)) ~ O(1)

Space complexity: O(log(x)) ~ O(1)




花花酱 LeetCode 189. Rotate Array


Given an array, rotate the array to the right by k steps, where k is non-negative.

Example 1:

Input: [1,2,3,4,5,6,7] and k = 3 
Output: [5,6,7,1,2,3,4]
Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] 
rotate 3 steps to the right: [5,6,7,1,2,3,4]

Example 2:

Input:[-1,-100,3,99] and k = 2 
Output: [3,99,-1,-100] 
Explanation: rotate 1 steps to the right: [99,-1,-100,3] rotate 2 steps to the right: [3,99,-1,-100]


  • Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
  • Could you do it in-place with O(1) extra space?

Solution 1: Simulate rotation with three reverses.

If k >= n, rotating k times has the same effect as rotating k % n times.

[1,2,3,4,5,6,7], K = 3


We can simulate the rotation with three reverses.

  1. reverse the whole array O(n) [7,6,5,4,3,2,1]
  2. reverse the left part 0 ~ k – 1 O(k) [5,6,7,4,3,2,1]
  3. reverse the right part k ~ n – 1 O(n-k) [5,6,7,1,2,3,4]

Time complexity: O(n)

Space complexity: O(1) in-place



花花酱 LeetCode 345. Reverse Vowels of a String


Write a function that takes a string as input and reverse only the vowels of a string.

Example 1:
Given s = “hello”, return “holle”.

Example 2:
Given s = “leetcode”, return “leotcede”.

The vowels does not include the letter “y”.



花花酱 LeetCode 541. Reverse String II



Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original.Example:

Input: s = "abcdefg", k = 2
Output: "bacdfeg"


  1. The string consists of lower English letters only.
  2. Length of the given string and k will in the range [1, 10000]



Related Problems

花花酱 LeetCode 206. Reverse Linked List



Reverse a singly linked list.

Solution 1:

Tracking prev / curr / next node

Time complexity: O(n)

Space complexity: O(1)



Python 3