Skip to content

Conversation

@krypton-io
Copy link
Contributor

Challenge 21 Solution

Submitted by: @krypton-io
Challenge: Challenge 21

Description

This PR contains my solution for Challenge 21.

Changes

  • Added solution file to challenge-21/submissions/krypton-io/solution-template.go

Testing

  • Solution passes all test cases
  • Code follows Go best practices

Thank you for reviewing my submission! 🚀

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 27, 2025

Walkthrough

This PR introduces a new Go file with three binary search functions: BinarySearch (iterative), BinarySearchRecursive (recursive), and FindInsertPosition (for maintaining sorted order). Each function operates on sorted integer slices with boundary optimizations and includes a main function demonstrating usage.

Changes

Cohort / File(s) Summary
Binary Search Implementation
challenge-21/submissions/krypton-io/solution-template.go
Added three exported search functions: BinarySearch (iterative binary search returning index or -1), BinarySearchRecursive (recursive variant with left/right bounds), and FindInsertPosition (insertion index calculation for sorted order). Includes main function with example usage and output.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

  • Verify correctness of iterative and recursive binary search logic, including boundary conditions
  • Validate FindInsertPosition insertion index calculation and edge cases
  • Check that all three functions properly handle empty/single-element slices

Possibly related PRs

Pre-merge checks

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title Check ✅ Passed The title "Add solution for Challenge 21 by krypton-io" directly corresponds to the main change in this pull request: the addition of a new solution file for Challenge 21 in the challenge-21/submissions/krypton-io/ directory. The title is specific, mentions both the challenge number and the contributor, and clearly summarizes the primary intent of the changeset without being vague or overly broad.
Description Check ✅ Passed The description is clearly related to the changeset, describing the addition of a solution file for Challenge 21 at the exact path where changes were made. It provides context about the submission, identifies the author, includes specific file changes, and notes that testing has been completed. While not extensive in detail, the description appropriately covers the scope of the PR and is directly relevant to the changeset.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (2)
challenge-21/submissions/krypton-io/solution-template.go (2)

29-29: Remove TODO comments.

The functions are implemented, so the TODO comments at lines 29, 70, and 105 should be removed.

Also applies to: 70-70, 105-105


69-100: Recursive implementation is correct.

The binary search logic and mid calculation (left + ((right - left) / 2)) are correct. The base case properly handles termination.

Minor optimization: the empty array check at lines 72-75 executes on every recursive call but only needs to run once. Consider moving it outside or removing it since invalid indices would be caught by the base case.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f7e24d8 and 934c305.

📒 Files selected for processing (1)
  • challenge-21/submissions/krypton-io/solution-template.go (1 hunks)

Comment on lines +49 to +62
for start != mid {

if target == arr[mid] {
return mid
}

if target < arr[mid] {
end = mid
mid /= 2
} else {
start = mid
mid = mid + ((end - mid) / 2)
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Critical: incorrect mid calculation breaks binary search.

Line 57 uses mid /= 2 when narrowing the search to the left half. This calculation ignores the start position and can cause mid to fall below start, accessing elements outside the valid search range.

Example: searching for 55 in [10, 20, 30, 40, 50, 60, 70, 80]:

  1. start=0, end=7, mid=3 → arr[3]=40 < 55
  2. start=3, end=7, mid=5 → arr[5]=60 > 55
  3. end=5, mid=2 (via line 57: 5/2=2) → mid < start!
  4. Algorithm now accesses arr[2]=30, outside valid range [3,5]

Apply this diff:

 	for start != mid  {
 	    
 	    if target == arr[mid] {
 	        return mid
 	    }
 	    
 	    if target < arr[mid] {
 	        end = mid
-	        mid /= 2
+	        mid = start + (end - start) / 2
 	    } else {
 	        start = mid
 	        mid = mid + ((end - mid) / 2)
 	    }
 	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
for start != mid {
if target == arr[mid] {
return mid
}
if target < arr[mid] {
end = mid
mid /= 2
} else {
start = mid
mid = mid + ((end - mid) / 2)
}
}
for start != mid {
if target == arr[mid] {
return mid
}
if target < arr[mid] {
end = mid
mid = start + (end - start) / 2
} else {
start = mid
mid = mid + ((end - mid) / 2)
}
}
🤖 Prompt for AI Agents
In challenge-21/submissions/krypton-io/solution-template.go around lines 49 to
62, the left-half branch sets mid via "mid /= 2", which ignores start and can
move mid below start; change the logic so after setting end = mid you recompute
mid relative to start, e.g. mid = start + (end - start)/2 (integer division),
ensuring mid stays within [start, end) and prevents out-of-range accesses.

Comment on lines +128 to +141
for start != mid {

if target == arr[mid] {
return mid
}

if target < arr[mid] {
end = mid
mid /= 2
} else {
start = mid
mid = mid + ((end - mid) / 2)
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Critical: incorrect mid calculation (same bug as BinarySearch).

Line 136 has the same critical bug as BinarySearch: mid /= 2 ignores the start position and can cause mid to fall below start, leading to incorrect array access.

Apply this diff:

 	for start != mid  {
 
 	    if target == arr[mid] {
 	        return mid
 	    }
 	    
 	    if target < arr[mid] {
 	        end = mid
-	        mid /= 2
+	        mid = start + (end - start) / 2
 	    } else {
 	        start = mid
 	        mid = mid + ((end - mid) / 2)
 	    }
 	}
🤖 Prompt for AI Agents
In challenge-21/submissions/krypton-io/solution-template.go around lines 128 to
141, the mid calculation is incorrect: when narrowing the search to the left
half the code does `mid /= 2`, which ignores `start` and can move mid below
start; replace both mid updates to compute the midpoint relative to start and
end (e.g., after setting end = mid compute mid = start + ((end - start) / 2),
and in the else branch after setting start = mid compute mid = start + ((end -
start) / 2)) so mid always stays within [start,end] and prevents invalid
accesses.

Comment on lines +143 to +151
if mid == 0 {
return 0
} else {
if(target < arr[mid]) {
return mid - 1
} else {
return mid + 1
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

Verify the insertion position logic.

The final adjustment returns mid - 1 when target < arr[mid] (line 147). This seems incorrect—if the target is less than the element at mid, it should typically be inserted at position mid, not mid - 1.

Please verify this logic is correct for all edge cases, especially when mid > 0.

Run the following test to verify the insertion position logic:


🏁 Script executed:

#!/bin/bash
# Test FindInsertPosition with various edge cases

cat > test_insert.go << 'EOF'
package main

import "fmt"

func FindInsertPosition(arr []int, target int) int {
	length := len(arr)
	start := 0
	end := length - 1
	mid := end / 2
	
	if length == 0 {
	    return 0
	}
	
	if target > arr[end] {
	    return end + 1
	}
	
	if target == arr[start] {
	    return start
	}
	
	if target == arr[end] {
	    return end
	}
	
	for start != mid  {

	    if target == arr[mid] {
	        return mid
	    }
	    
	    if target < arr[mid] {
	        end = mid
	        mid /= 2
	    } else {
	        start = mid
	        mid = mid + ((end - mid) / 2)
	    }
	}
	
	if mid == 0 {
	    return 0
	} else {
	   if(target < arr[mid]) {
	       return mid - 1
	   } else {
	       return mid + 1
	   }
	}
}

func main() {
	testCases := []struct{
		arr []int
		target int
		expected int
	}{
		{[]int{1,3,5,7,9}, 4, 2},
		{[]int{1,3,5,7,9}, 6, 3},
		{[]int{1,3,5,7,9}, 2, 1},
		{[]int{1,3,5,7,9}, 0, 0},
		{[]int{2,4,6,8}, 5, 2},
		{[]int{10,20,30,40,50}, 25, 2},
	}
	
	for _, tc := range testCases {
		result := FindInsertPosition(tc.arr, tc.target)
		status := "✓"
		if result != tc.expected {
			status = "✗"
		}
		fmt.Printf("%s Insert %d in %v: got %d, expected %d\n", 
			status, tc.target, tc.arr, result, tc.expected)
	}
}
EOF

go run test_insert.go
rm test_insert.go

Length of output: 374


Fix insertion position return values at lines 147 and 149.

The test confirms a bug: inserting 2 into [1,3,5,7,9] returns 0 instead of the correct position 1. The logic incorrectly returns mid - 1 when target < arr[mid], when it should return mid (the correct insertion point before the larger element). Similarly, line 149 should return mid instead of mid + 1.

	if mid == 0 {
	    return 0
	} else {
	   if(target < arr[mid]) {
	       return mid
	   } else {
	       return mid
	   }
	}
🤖 Prompt for AI Agents
In challenge-21/submissions/krypton-io/solution-template.go around lines 143 to
151, the insertion-position logic is wrong: when mid != 0 the code returns mid-1
or mid+1 causing incorrect positions (e.g., inserting 2 into [1,3,5,7,9] yields
0). Change the two return statements on lines 147 and 149 so both return mid
(i.e., when mid != 0 always return mid), leaving the existing mid==0 return
as-is; you can also simplify by removing the inner if and just returning mid for
the non-zero case.

@RezaSi RezaSi merged commit 9f9c1f9 into RezaSi:main Oct 28, 2025
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants