Longest Alternating Substring Given a string of digits, return the longest substring with alternating odd/even or even/odd digits. If two or more substrings have the same length, return the substring that occurs first.

Examples longest_substring("225424272163254474441338664823") ➞ "272163254"

# substrings = 254, 272163254, 474, 41, 38, 23

longest_substring("594127169973391692147228678476") ➞ "16921472"

# substrings = 94127, 169, 16921472, 678, 476

longest_substring("721449827599186159274227324466") ➞ "7214"

# substrings = 7214, 498, 27, 18, 61, 9274, 27, 32

# 7214 and 9274 have same length, but 7214 occurs first.

Notes The minimum alternating substring size is 2, and there will always be at least one alternating substring.

in python

Here is a Python solution for finding the longest alternating substring of digits:

python
def longest_substring(s):
    def is_odd(digit):
        return int(digit) % 2 == 1

    longest = ''
    current = s[0]

    for i in range(1, len(s)):
        if is_odd(s[i-1]) != is_odd(s[i]):
            current += s[i]
            if len(current) > len(longest):
                longest = current
        else:
            current = s[i]

    return longest

# Test cases
print(longest_substring("225424272163254474441338664823"))  # ➞ "272163254"
print(longest_substring("594127169973391692147228678476"))  # ➞ "16921472"
print(longest_substring("721449827599186159274227324466"))  # ➞ "7214"				
			
		

Explanation:

  • The function is_odd checks if a digit is odd.
  • longest keeps track of the longest alternating substring found so far.
  • current keeps track of the current alternating substring being built.
  • We iterate through the string s, starting from the second character.
  • If the current digit and the previous digit have different parity (one is odd and the other is even), we append the current digit to current and check if current is longer than longest.
  • If they have the same parity, we start a new substring with the current digit.
  • At the end, longest will contain the longest alternating substring.

This solution has a time complexity of O(n), where n is the length of the input string.

Caesar's Cipher Julius Caesar protected his confidential information by encrypting it using a cipher. Caesar's cipher (check Resources tab for more info) shifts each letter by a number of letters. If the shift takes you past the end of the alphabet, just rotate back to the front of the alphabet. In the case of a rotation by 3, w, x, y and z would map to z, a, b and c.

Create a function that takes a string s (text to be encrypted) and an integer k (the rotation factor). It should return an encrypted string.

Examples caesarCipher("middle-Outz", 2) ➞ "okffng-Qwvb"

// m -> o // i -> k // d -> f // d -> f // l -> n // e -> g // - - // O -> Q // u -> w // t -> v // z -> b

caesarCipher("Always-Look-on-the-Bright-Side-of-Life", 5) ➞ "Fqbfdx-Qttp-ts-ymj-Gwnlmy-Xnij-tk-Qnkj"

caesarCipher("A friend in need is a friend indeed", 20) ➞ "U zlcyhx ch hyyx cm u zlcyhx chxyyx" Notes All test input will be a valid ASCII string.

in JavaScript

Here is a JavaScript function that implements Caesar's Cipher:

javascript
function caesarCipher(s, k) {
    // Normalize k to be within 0-25
    k = k % 26;

    let result = '';

    for (let i = 0; i < s.length; i++) {
        let charCode = s.charCodeAt(i);

        // Check if it's an uppercase letter
        if (charCode >= 65 && charCode <= 90) {
            result += String.fromCharCode((charCode - 65 + k) % 26 + 65);
        }
        // Check if it's a lowercase letter
        else if (charCode >= 97 && charCode <= 122) {
            result += String.fromCharCode((charCode - 97 + k) % 26 + 97);
        }
        // If it's not a letter, just append it as is
        else {
            result += s[i];
        }
    }

    return result;
}

// Test cases
console.log(caesarCipher("middle-Outz", 2));  // ➞ "okffng-Qwvb"
console.log(caesarCipher("Always-Look-on-the-Bright-Side-of-Life", 5));  // ➞ "Fqbfdx-Qttp-ts-ymj-Gwnlmy-Xnij-tk-Qnkj"
console.log(caesarCipher("A friend in need is a friend indeed", 20));  // ➞ "U zlcyhx ch hyyx cm u zlcyhx chxyyx"				
			
		

Explanation:

  • Normalize k: Since the alphabet has 26 letters, we use k % 26 to ensure k is within the range 0-25.
  • Loop through each character:
    • Uppercase letters: Convert to ASCII, shift, wrap around using modulo, and convert back to character.
    • Lowercase letters: Same process as uppercase.
    • Non-letters: Append as is (e.g., spaces, punctuation).
  • Return the result: The encrypted string is built character by character and returned at the end.

This function handles both uppercase and lowercase letters, and leaves non-alphabetic characters unchanged.

Message from Space You have received an encrypted message from space. Your task is to decrypt the message with the following simple rules:

Message string will consist of capital letters, numbers, and brackets only. When there's a block of code inside the brackets, such as [10AB], it means you need to repeat the letters AB for 10 times. Message can be embedded in multiple layers of blocks. Final decrypted message will only consist of capital letters. Create a function that takes encrypted message str and returns the decrypted message.

Examples spaceMessage("ABCD") ➞ "ABCD"

spaceMessage("AB[3CD]") ➞ "ABCDCDCD" // "AB" = "AB" // "[3CD]" = "CDCDCD"

spaceMessage("IF[2E]LG[5O]D") ➞ "IFEELGOOOOOD"

in C++

Here's a C++ function to decrypt the message from space according to the given rules:

cpp
#include <iostream>
#include <string>
#include <stack>

std::string spaceMessage(const std::string& encrypted) {
    std::stack<int> countStack;
    std::stack<std::string> stringStack;
    int count = 0;
    std::string currentString = "";
    std::string result = "";

    for (char c : encrypted) {
        if (isdigit(c)) {
            count = count * 10 + (c - '0');
        } else if (c == '[') {
            countStack.push(count);
            stringStack.push(currentString);
            count = 0;
            currentString = "";
        } else if (c == ']') {
            int repeatCount = countStack.top();
            countStack.pop();
            std::string temp = currentString;
            currentString = stringStack.top();
            stringStack.pop();
            for (int i = 0; i < repeatCount; ++i) {
                currentString += temp;
            }
        } else {
            currentString += c;
        }
    }

    result += currentString;
    return result;
}

int main() {
    std::cout << spaceMessage("ABCD") << std::endl;          // Output: "ABCD"
    std::cout << spaceMessage("AB[3CD]") << std::endl;       // Output: "ABCDCDCD"
    std::cout << spaceMessage("IF[2E]LG[5O]D") << std::endl; // Output: "IFEELGOOOOOD"
    return 0;
}				
			
		

Explanation:

  • Stacks: We use two stacks:
    • countStack to keep track of the number of repetitions.
    • stringStack to store the current string before encountering a new block.
  • Loop through the string:
    • If the character is a digit, we build the count.
    • If it's an opening bracket [, we push the count and current string onto their respective stacks, and reset both.
    • If it's a closing bracket ], we pop the count and previous string, repeat the current string, and append it to the previous string.
    • If it's any other character (a letter), we append it to the current string.
  • Result: After processing the entire string, the final decrypted message is stored in currentString.

This approach handles nested brackets and multiple blocks correctly.

Asteroid Collision You are given an array asteroids of integers representing asteroids in a row.

For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.

Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.

Examples asteroidCollision([-2, -1, 1, 2]) ➞ [-2, -1, 1, 2]

asteroidCollision([-2, 1, 1, -2]) ➞ [-2, -2]

asteroidCollision([1, 1, -2, -2]) ➞ [-2, -2]

asteroidCollision([10, 2, -5]) ➞ [10]

asteroidCollision([8, -8]) ➞ [] Notes BONUS: Use only one loop (either for or while).

in C++

Here is a C++ solution for the asteroid collision problem using a stack to efficiently handle the collisions:

cpp
#include <iostream>
#include <vector>
#include <stack>
using namespace std;

vector<int> asteroidCollision(vector<int>& asteroids) {
    stack<int> st;
    for (int asteroid : asteroids) {
        bool destroyed = false;
        while (!st.empty() && asteroid < 0 && st.top() > 0) {
            if (st.top() < -asteroid) {
                st.pop();
                continue;
            } else if (st.top() == -asteroid) {
                st.pop();
            }
            destroyed = true;
            break;
        }
        if (!destroyed) {
            st.push(asteroid);
        }
    }

    vector<int> result(st.size());
    for (int i = st.size() - 1; i >= 0; --i) {
        result[i] = st.top();
        st.pop();
    }
    return result;
}

int main() {
    vector<int> asteroids1 = {-2, -1, 1, 2};
    vector<int> result1 = asteroidCollision(asteroids1);
    for (int asteroid : result1) {
        cout << asteroid << " ";
    }
    cout << endl;

    vector<int> asteroids2 = {-2, 1, 1, -2};
    vector<int> result2 = asteroidCollision(asteroids2);
    for (int asteroid : result2) {
        cout << asteroid << " ";
    }
    cout << endl;

    vector<int> asteroids3 = {1, 1, -2, -2};
    vector<int> result3 = asteroidCollision(asteroids3);
    for (int asteroid : result3) {
        cout << asteroid << " ";
    }
    cout << endl;

    vector<int> asteroids4 = {10, 2, -5};
    vector<int> result4 = asteroidCollision(asteroids4);
    for (int asteroid : result4) {
        cout << asteroid << " ";
    }
    cout << endl;

    vector<int> asteroids5 = {8, -8};
    vector<int> result5 = asteroidCollision(asteroids5);
    for (int asteroid : result5) {
        cout << asteroid << " ";
    }
    cout << endl;

    return 0;
}				
			
		

Explanation:

  • Stack Usage: We use a stack to keep track of the surviving asteroids.
  • Collision Logic:
    • If the current asteroid is moving left (asteroid < 0) and the top of the stack is moving right (st.top() > 0), they will collide.
    • If the right-moving asteroid is smaller, it explodes (st.pop()).
    • If they are the same size, both explode (st.pop() and destroyed = true).
    • If the left-moving asteroid is smaller, it explodes (destroyed = true).
  • Surviving Asteroids: If the current asteroid is not destroyed, we push it onto the stack.
  • Result Construction: After processing all asteroids, we construct the result vector from the stack (in reverse order).

This solution uses only one loop (the for loop) to iterate through the asteroids, and handles all collisions within the loop using the stack.

Caesar's Cipher Julius Caesar protected his confidential information by encrypting it using a cipher. Caesar's cipher (check Resources tab for more info) shifts each letter by a number of letters. If the shift takes you past the end of the alphabet, just rotate back to the front of the alphabet. In the case of a rotation by 3, w, x, y and z would map to z, a, b and c.

Create a function that takes a string s (text to be encrypted) and an integer k (the rotation factor). It should return an encrypted string.

Examples caesarCipher("middle-Outz", 2) ➞ "okffng-Qwvb"

// m -> o // i -> k // d -> f // d -> f // l -> n // e -> g // - - // O -> Q // u -> w // t -> v // z -> b

caesarCipher("Always-Look-on-the-Bright-Side-of-Life", 5) ➞ "Fqbfdx-Qttp-ts-ymj-Gwnlmy-Xnij-tk-Qnkj"

caesarCipher("A friend in need is a friend indeed", 20) ➞ "U zlcyhx ch hyyx cm u zlcyhx chxyyx" Notes All test input will be a valid ASCII string.

in C++

Here is a C++ function to implement Caesar's Cipher:

cpp
#include <iostream>
#include <string>

std::string caesarCipher(const std::string& s, int k) {
    // Normalize k to be within 0-25
    k = k % 26;

    std::string result;
    for (char c : s) {
        if (isupper(c)) {
            // Shift uppercase letters
            result += (c - 'A' + k + 26) % 26 + 'A';
        } else if (islower(c)) {
            // Shift lowercase letters
            result += (c - 'a' + k + 26) % 26 + 'a';
        } else {
            // Non-alphabetic characters are not changed
            result += c;
        }
    }
    return result;
}

int main() {
    std::cout << caesarCipher("middle-Outz", 2) << std::endl;  // Output: "okffng-Qwvb"
    std::cout << caesarCipher("Always-Look-on-the-Bright-Side-of-Life", 5) << std::endl;  // Output: "Fqbfdx-Qttp-ts-ymj-Gwnlmy-Xnij-tk-Qnkj"
    std::cout << caesarCipher("A friend in need is a friend indeed", 20) << std::endl;  // Output: "U zlcyhx ch hyyx cm u zlcyhx chxyyx"

    return 0;
}				
			
		

Explanation:

  • Normalize k: Since there are 26 letters in the alphabet, k % 26 ensures that k is within the range 0-25.
  • Loop through each character:
    • Uppercase letters: Convert to 0-25 range, add k, wrap around using modulo, and convert back to uppercase.
    • Lowercase letters: Same process as uppercase, but for lowercase letters.
    • Non-alphabetic characters: Append them as is (e.g., spaces, punctuation).
  • Return the result: The encrypted string is built character by character and returned at the end.

This function correctly handles both uppercase and lowercase letters, and leaves non-alphabetic characters unchanged.

A.X Chat은 대화 내용을 저장하지 않으며, 메시지를 보내시면 저희의 이용약관 및 개인정보 보호 정책에 동의하시게 됩니다.
현재의 A.X Chat은 LLM 서비스이며, Agent·Image 등의 기술 연동이 필요하시면 a.x@sk.com으로 문의해 주세요.