101 Logo
onenoughtone

Code Implementation

Message Encryption Implementation

Below is the implementation of the message encryption:

solution.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
function reverseString(s) {
// Convert string to array (strings are immutable in JavaScript)
const chars = s.split('');
// Two pointers approach
let left = 0;
let right = chars.length - 1;
while (left < right) {
// Swap characters
const temp = chars[left];
chars[left] = chars[right];
chars[right] = temp;
// Move pointers towards the middle
left++;
right--;
}
// Convert array back to string
return chars.join('');
}
// Alternative approach using built-in methods
function reverseStringAlt(s) {
return s.split('').reverse().join('');
}
// Test cases
console.log(reverseString("hello")); // "olleh"
console.log(reverseString("Secure Message")); // "egasseM eruceS"
console.log(reverseString("Agent 007")); // "700 tnegA"

Step-by-Step Explanation

Let's break down the implementation:

  1. Initialize Pointers: Set up two pointers: one at the beginning of the string (left) and one at the end (right).
  2. Swap Characters: Swap the characters at the left and right positions using a temporary variable.
  3. Move Pointers: Increment the left pointer and decrement the right pointer to move them toward the center.
  4. Repeat Until Done: Continue swapping and moving pointers until they meet or cross each other.
  5. Return Result: Return the modified string, which is now reversed.
ProblemSolutionCode
101 Logo
onenoughtone