Starts With
Write a TypeScript function that checks if a string starts with a given prefix. Do not use the built-in startsWith() method — implement the logic manually.
If the prefix is longer than the string, return false. Loop through the prefix characters and compare with the corresponding characters in the string at the same positions. If all characters match, return true.
Edge cases include empty prefix (return true), empty string with non-empty prefix (return false), and case-sensitive comparison.
The prefix check algorithm compares characters one by one from the beginning. If any character mismatches, the function returns false immediately. This early exit optimization provides O(1) best-case performance when the first character differs.
TypeScript's boolean return type ensures the function always returns true or false. The length check at the beginning prevents out-of-bounds access when the prefix is longer than the text.
Edge cases include empty prefix (always returns true), empty string with non-empty prefix (returns false), and exact matches where the prefix equals the entire string.
The prefix check algorithm compares characters one by one from the beginning. If any character mismatches, the function returns false immediately. This early exit optimization provides O(1) best-case performance when the first character differs.
TypeScript's boolean return type ensures the function always returns true or false. The length check at the beginning prevents out-of-bounds access when the prefix is longer than the text.
Edge cases include empty prefix (always returns true), empty string with non-empty prefix (returns false), and exact matches where the prefix equals the entire string. The charAt() method is used for character comparison.
Example Input & Output
Algorithm Flow

Solution Approach
If prefix.length > text.length, return false. Loop from 0 to prefix.length - 1. If text.charAt(i) !== prefix.charAt(i), return false. After the loop, return true.
The time complexity is O(m) where m is the prefix length. Space complexity is O(1).
Best Answers
function startsWith(text: string, prefix: string): boolean {
if (prefix.length > text.length) return false;
for (var i = 0; i < prefix.length; i++) {
if (text.charAt(i) !== prefix.charAt(i)) return false;
}
return true;
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
