Equal Beauty CodeChef SnackDown 2021 Round 1A Question The beauty of an (non-empty) array of integers is defined as the difference between its largest and smallest element. For example, the beauty of the array [2,3,4,4,6] is 6−2=4. An array A is said to be good if it is possible to partition the elements of A into two non-empty arrays B1 and B2 such that B1 and B2 have the same beauty. Each element of array A should be in exactly one array: either in B1 or in B2. For example, the array [6,2,4,4,4] is good because its elements can be partitioned into two arrays B1=[6,4,4] and B2=[2,4], where both B1 and B2 have the same beauty (6−4=4−2=2). You are given an array A of length N. In one move you can: Select an index i (1≤i≤N) and either increase Ai by 1 or decrease Ai by 1. Find the minimum number of moves required to make the array A good. Input Format The first line of input contains a single integer T, denoting the number of test cases. The description of T test cases follow. Each ...
Reverse Words in a String LeetCode Solution
Question
Given an input string s
, reverse the order of the words.
A word is defined as a sequence of non-space characters. The words in s
will be separated by at least one space.
Return a string of the words in reverse order concatenated by a single space.
Note that s
may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.
Example 1:
Input: s = "the sky is blue" Output: "blue is sky the"
Example 2:
Input: s = " hello world " Output: "world hello" Explanation: Your reversed string should not contain leading or trailing spaces.
Example 3:
Input: s = "a good example" Output: "example good a" Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
Example 4:
Input: s = " Bob Loves Alice " Output: "Alice Loves Bob"
Example 5:
Input: s = "Alice does not even like bob" Output: "bob like even not does Alice"
Constraints:
1 <= s.length <= 104
s
contains English letters (upper-case and lower-case), digits, and spaces' '
.- There is at least one word in
s
.
Follow-up: If the string data type is mutable in your language, can you solve it in-place with O(1)
extra space?
Explanation
This question is from the medium category of LeetCode. This question can be solved in multiple ways using multiple approaches. We can not do better than O(n) space in python, because strings are immutable. However if we are given not string, but array of symbols, we can remove all extra spaces, using Two pointers approach, reverse full string and then reverse each word. Time complexity will be O(n) and space will be O(1). Here is the python code: We traverse chars with two pointers and rewrite symbols in the beginning. Cut our chars, removing last elements (in my code it is not really inplace, but you can use del to do it in place), Reverse list using chars.reverse(). Use two pointers to reverse each word. If you use python, this problem becomes not medium, but rather easy: all you need to do is to split() you data and take elements in negative order. split() is smart enough to ignore several spaces in a row as well as extra spaces in the begin and in the end. Complexity: both time and memory complexity is O(n), because we traverse all string and we create new with size O(n). The following is 2 different solutions Iterates String Backwards, Iterates String Forwards using a Stack. The idea here is to iterate the source string backwards, creating word segments, and saving those found word segments to a result string. For each loop iteration in the source string, the letter at the current index is appended to the current word segment. When a whitespace is encountered, that means the current word segment is complete, and it is then added to the result string. This process continues until all characters in the source string has been iterated. The idea here is the same as above, but instead of iterating backwards, the source string is iterated forwards. When a word segment is found, it is saved to the stack. For each loop iteration in the source string, the letter at the current index is appended to the current word segment. When a whitespace is encountered, that means the current word segment is complete, and it is then added to the stack. This process continues until all characters in the source string has been iterated.
Append all word segments from the stack to the result string. They will be in reverse order when appended. That's all you needed to understand, now code it. I recommend first to try yourself then if you are stuck you can visit the solutions below in Java, C++, Python, C#.
Program Code
Java
Using StringBuilder Function
class Solution {
public String reverseWords(String s) {
StringBuilder result = new StringBuilder();
StringBuilder current = new StringBuilder();
int N = s.length();
for(int i = N - 1; i >= 0; i--) {
current.setLength(0);
while(i >= 0 && s.charAt(i) != ' ') {
current.append(s.charAt(i));
i--;
}
if(current.length() > 0) {
result.append(result.length() == 0 ? "": " ");
result.append(current.reverse().toString());
}
}
return result.toString();
}
}
Without using StringBuilder Function
class Solution {
public String reverseWords(String s) {
String result = "";
String current = "";
int N = s.length();
for(int i = N - 1; i >= 0; i--) {
current = "";
while(i >= 0 && s.charAt(i) != ' ') {
current = s.charAt(i) + current;
i--;
}
if(current.length() > 0) {
result += (result.length() == 0 ? "": " ") + current;
}
}
return result;
}
}
C++
Using stringstream() function
class Solution {
public:
string reverseWords(string s) {
vector<string> vec;
stringstream str(s);
string word;
while (str >> word) // store separated words in vector
vec.push_back(word);
reverse(vec.begin(), vec.end()); // reverse vector
string res;
for (const auto &it : vec) // concatenate strings
res += " " + it;
res.erase(0,1); // first place is always a space - extra
return res;
}
};
Without using stringstream() function
class Solution {
public:
string reverseWords(string s) {
//Remove trailing and leading spaces
while(s[0] == ' ')
s.erase(s.begin());
int i = s.length() - 1;
while(s[i] == ' ')
{
s.erase(s.begin()+i);
i--;
}
//Remove extra spaces in string
for(int i = 1; i< s.length(); i++)
{
while(s[i] == s[i-1] && s[i] == ' ')
s.erase(s.begin()+i);
}
//reverse whole string
reverse(s.begin(),s.end());
//reverse the word using two pointers
int j = 0;
for(int i = 1; i<s.length(); i++)
{
if(s[i-1] == ' ')
j = i; //store new word index in j
else if(s[i] != ' ')
continue;
else
reverse(s.begin()+j, s.begin()+i); //reverse the word between i and j
}
reverse(s.begin()+j, s.end()); //reverse the last word
return s;
}
};
Python
Using Two pointer
class Solution:
def reverseWords(self, s):
chars = [t for t in s]
slow, n = 0, len(s)
for fast in range(n):
if chars[fast] != " " or (fast > 0 and chars[fast] == " " and chars[fast-1] != " "):
chars[slow] = chars[fast]
slow += 1
if slow == 0: return ""
chars = chars[:slow-1] if chars[-1] == " " else chars[:slow]
chars.reverse()
slow, m = 0, len(chars)
for fast in range(m + 1):
if fast == m or chars[fast] == " ":
chars[slow:fast] = chars[slow:fast][::-1]
slow = fast + 1
return "".join(chars)
Using split() function
class Solution:
def reverseWords(self, s):
return " ".join(s.split()[::-1])
C#
Iterating backwards
public class Solution {
public string ReverseWords(string s) {
// Add a space at the beginning which indicates the end of data
s = " " + s;
var result = new StringBuilder();
var word = new StringBuilder();
// Iterate starting from the end of the string to
// isolate word segments and place all the found
// segments into result
for (int index = s.Length -1; index >= 0; --index) {
// Get the current letter
var letter = s[index];
// Add letter to current word segment if its not a whitespace
if (!char.IsWhiteSpace(letter)) {
// Add letter to the begining of the word
word.Insert(0, letter);
} else if (word.Length > 0) {
// The letter was a whitespace, append word segment to result
if (result.Length > 0) {
result.Append(" ");
}
result.Append(word.ToString());
// Start a new word segment
word.Clear();
}
}
return result.ToString();
}
}
Iterating forwards
public class Solution {
public string ReverseWords(string s) {
// Add a space at the end which indicates the end of data
s += " ";
var stack = new Stack<string>();
var word = new StringBuilder();
// Isolate word segments and place into a stack
for (int index = 0; index < s.Length; ++index) {
// Get the current letter
var letter = s[index];
// Add letter to current word segment if its not a whitespace
if (!char.IsWhiteSpace(letter)) {
word.Append(letter);
} else if (word.Length > 0) {
// The letter was a whitespace, add the word segment to the stack
stack.Push(word.ToString());
// Start a new word segment
word.Clear();
}
}
// Get data from the stack and add to result
var result = new StringBuilder();
while (stack.Count > 0) {
if (result.Length > 0) {
result.Append(" ");
}
result.Append(stack.Peek());
stack.Pop();
}
return result.ToString();
}
}
Comments
Post a Comment