Physical Address
Mirpur,
Dhaka, Bangladesh
Physical Address
Mirpur,
Dhaka, Bangladesh

Given an array ofNnumbers, and rotation position, need to build a new array after rotation position of elements that rotated left into array.
For example:
Given Array: [1, 2, 3, 4, 5], Rotation Position: 2
Expected Output: [3, 4, 5, 1, 2]
In this problem, we have an array of integers and a rotation position. Rotation position means we need to rotate the array to left after rotation position of array, and return the new array with the rest of it.
Initial Approach:
/**
* Initial Approach
* Rotate array without built-in function – Rotate left after rotation position of array
* @param array $arr
* @param $position
* @return array
*/
function rotateLeft(array $arr, $position): array
{
// It iterates nth number times
for ($i = 0; $i < $position; $i++) {
// Stores the first element of the array
$first = $arr[0];
// Build an array by shifting the position of items
for($j = 0; $j < count($arr)-1; $j++) {
$arr[$j] = $arr[$j+1];
}
// First element of array will be added to the end
$arr[$j] = $first;
}
return $arr;
}
// Example Usage:
$array = [1, 2, 3, 4, 5];
$rotated = rotateLeft($array, 2);
print_r($rotated); // Output: [3, 4, 5, 1, 2]
Time Complexity Analysis of Initial Approach:
Approach1 has O(n × k) time complexity where:
n = array length
k = rotation position
Breakdown:
Outer Loop: runs k times
Inner Loop: runs (n-1) times for each outer iteration
Total: O(k × n)
Space Complexity: O(1) — modifies array in place
Issues with Initial Approach:
Inefficient: For large arrays or large rotation values, this becomes very slow
Redundant work: Each rotation moves every element, even when doing multiple rotations
/**
* Optimized Approach
* @param array $arr
* @param $position
* @return array
*/
function rotateLeft(array $arr, $position): array
{
$n = count($arr);
// Handle edge cases
if ($n <= 1 || $position <= 0) {
return $arr;
}
// Optimize: position might be larger than array length
$position = $position % $n;
if ($position == 0) {
return $arr;
}
$result = [];
// Copy elements from position to end
for ($i = $position; $i < $n; $i++) {
$result[] = $arr[$i];
}
// Copy elements from start to position
for ($i = 0; $i < $position; $i++) {
$result[] = $arr[$i];
}
return $result;
}
// Example Usage:
$array = [1, 2, 3, 4, 5];
$rotated = rotateLeft($array, 2);
print_r($rotated); // Output: [3, 4, 5, 1, 2]
Initial Approach: O(n × k) time, O(1) space
Optimized Approach: O(n) time, O(n) space
Example: For array of 1000 elements with rotation of 500:
Initial Approach: ~500,000 operations
Optimized Approach: ~1,000 operations
The optimized version is significantly faster, especially for larger arrays or rotation values, though it uses additional space for the result array.