Last Index of One
Problem​
Given a string S consisting only '0's and '1's, find the last index of the '1' present in it.
Examples:​
Example 1:
Input:
S = 00001
Output:
4
Explanation:
Last index of 1 in given string is 4.
Example 2:
Input:
0
Output:
-1
Explanation:
Since, 1 is not present, so output is -1.
Your task:​
You don't need to read input or print anything. Your task is to complete the function lastIndex() which takes the string S as inputs and returns the last index of '1'. If '1' is not present, return "-1" (without quotes).
- Expected Time Complexity:
- Expected Auxiliary Space:
Constraints:​
Solution​
Python​
def lastIndex(self, s):
index = -1
for i in range(0, len(s)):
if s[i] == '1':
index = i
return index
Java​
public int lastIndex( String s) {
int index = -1;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '1') {
index = i;
}
}
return index;
}
C++​
int lastIndex(string s) {
int index = -1;
for (int i = 0; i < s.length(); i++) {
if (s[i] == '1') {
index = i;
}
}
return index;
}
C​
int lastIndex(const char *s) {
int index = -1;
int length = strlen(s);
for (int i = 0; i < length; i++) {
if (s[i] == '1') { instead of integer 1
index = i;
}
}
return index;
}
- Time Complexity:
- Auxiliary Space: