#include <string>
#include <iostream>
using namespace std;
/*
Write a function that takes in a string and returns the length of the longest
prefix in which all characters are arranged in alphabetical order.
Examples:
alphaprefix("ransom") = 1
alphaprefix("google") = 3
alphaprefix("knotty") = 6
*/
int alphaprefix(string input) {
if(input.size() <= 1) return input.size();
int maxLen = 1;
int len = 1;
for(int i = 1; i < input.size(); ++i) {
if(input[i] >= input[i-1]) len++;
else break;
}
return len;
}
int main(void) {
cout << alphaprefix("ransom") << endl;
cout << alphaprefix("google") << endl;
cout << alphaprefix("knotty") << endl;
}
This one is very similar to LeetCode's recover IP Address question, but much simpler!
#include <iostream>
#include <vector>
using namespace std;
/*
You are given a int[N] array num, count how many triplets(x, y, z) that
num[x] + num[y] + num[z] < K
Assuming x < y < z
For example:
num[] = {5, 3, 6, 1, 8, 10}, K = 13
5 + 3 + 1 = 9 < 13
5 + 6 + 1 = 12 < 13
3 + 6 + 1 = 10 < 13
3 + 1 + 8 = 12 < 13 ----> return 4.
*/
int countTriplets(vector<int>& nums, int K) {
if(nums.size() < 3) return 0;
int count = 0;
for(int i = 0; i < nums.size() - 2; ++i) {
int target = nums[i];
for(int j = i + 1; j < nums.size() - 1; ++j) {
target += nums[j];
for(int k = j + 1; k < nums.size(); ++k) {
target += nums[k];
if(target < K) {
count++;
}
target -= nums[k];
}
target -= nums[j];
}
}
return count;
}
// Thought about it a bit. It seems that sort the nums doesn't actually affect the result.
// The interviewer only asked for the final number. when we chose 3 numbers, they will always
// have x < y < z
int sortCountTriplets(vector<int>& nums, int K) {
if(nums.size() < 3) return 0;
sort(nums.begin(), nums.end());
int count = 0;
for(int i = 0; i < nums.size() - 2; ++i) {
int start = i + 1;
int end = nums.size() - 1;
while(start < end) {
int sum = nums[i] + nums[start] + nums[end];
if(sum < K) {
count += end - start;
start++;
} else end--;
}
}
return count;
}
int main(void) {
vector<int> nums{5, 3, 6, 1, 8, 10};
cout << countTriplets(nums, 13) << endl;
}