101 Logo
onenoughtone

Code Implementation

DNA Sequence Analysis Implementation

Below is the implementation of the dna sequence analysis:

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
function longestCommonPrefix(strs) {
// Handle edge cases
if (strs.length === 0) return "";
if (strs.length === 1) return strs[0];
// Approach 1: Horizontal scanning
let prefix = strs[0];
for (let i = 1; i < strs.length; i++) {
// Keep reducing the prefix until it's a prefix of the current string
while (strs[i].indexOf(prefix) !== 0) {
prefix = prefix.substring(0, prefix.length - 1);
if (prefix === "") return "";
}
}
return prefix;
}
// Alternative approach: Vertical scanning
function longestCommonPrefixAlt(strs) {
// Handle edge cases
if (strs.length === 0) return "";
if (strs.length === 1) return strs[0];
// Find the minimum length string
let minLength = Infinity;
for (let str of strs) {
minLength = Math.min(minLength, str.length);
}
// Compare characters at the same position
let result = "";
for (let i = 0; i < minLength; i++) {
const char = strs[0][i];
for (let j = 1; j < strs.length; j++) {
if (strs[j][i] !== char) {
return result;
}
}
result += char;
}
return result;
}
// Test cases
console.log(longestCommonPrefix(["ACGTGGT", "ACGTCAT", "ACGTTGA"])); // "ACGT"
console.log(longestCommonPrefix(["GAATTC", "GATTACA", "GATAGC"])); // "GA"
console.log(longestCommonPrefix(["TGCAA", "ATCGA", "CGTAT"])); // ""

Step-by-Step Explanation

Let's break down the implementation:

  1. Handle Edge Cases: Check for empty array or single string cases and return appropriate results.
  2. Initialize Prefix: Start with the first string as the assumed longest common prefix.
  3. Iterate Through Strings: For each string in the array, compare it with the current prefix.
  4. Reduce Prefix: If the current string doesn't start with the prefix, reduce the prefix by one character at a time.
  5. Check for Empty Prefix: If the prefix becomes empty at any point, return an empty string as there is no common prefix.
ProblemSolutionCode
101 Logo
onenoughtone