The Wayback Machine - https://web.archive.org/web/20240717180655/https://www.geeksforgeeks.org/find-middle-point-segment-from-given-segment-lengths/
Open In App

Find middle point segment from given segment lengths

Last Updated : 12 Sep, 2022
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

Given an array arr[] of size M. The array represents segment lengths of different sizes. These segments divide a line beginning with 0. The value of arr[0] represents a segment from 0 arr[0], value of arr[1] represents segment from arr[0] to arr[1], and so on. 
The task is to find the segment which contains the middle point, If the middle segment does not exist, print ‘-1’.

Examples: 

Input: arr = {3, 2, 8} 
Output: 3 
The three segments are (0, 3), (3, 5), (5, 13) 
middle point is 6.5 which is in the 3rd segment. 

Input: arr = {3, 2, 5} 
Output: -1 
Middle point is 5 which is between segments 2 and 3. 

Approach: The middle point will always be N / 2. Now, check in which segment does this point exist and print the segment number. If it is the starting or ending for any segment then print ‘-1’.

Below is the implementation of the above approach:

C++




// C/C++ implementation of the approach
#include <iostream>
using namespace std;
 
// Function that returns the segment for the
// middle point
int findSegment(int n, int m, int segment_length[])
{
 
    // the middle point
    double meet_point = (1.0 * n) / 2.0;
    int sum = 0;
 
    // stores the segment index
    int segment_number = 0;
 
    for (int i = 0; i < m; i++) {
 
        // increment sum by
        // length of the segment
        sum += segment_length[i];
 
        // if the middle is
        // in between two segments
        if ((double)sum == meet_point) {
            segment_number = -1;
            break;
        }
 
        // if sum is greater
        // than middle point
        if (sum > meet_point) {
            segment_number = i + 1;
            break;
        }
    }
 
    return segment_number;
}
 
// Driver code
int main()
{
    int n = 13;
    int m = 3;
    int segment_length[] = { 3, 2, 8 };
 
    int ans = findSegment(n, m, segment_length);
    cout << (ans);
 
    return 0;
}


Java




// Java implementation of the approach
class GFG {
 
    // Function that returns the segment for the
    // middle point
    static int findSegment(int n, int m,
                           int[] segment_length)
    {
 
        // the middle point
        double meet_point = (1.0 * n) / 2.0;
        int sum = 0;
 
        // stores the segment index
        int segment_number = 0;
 
        for (int i = 0; i < m; i++) {
 
            // increment sum by
            // length of the segment
            sum += segment_length[i];
 
            // if the middle is
            // in between two segments
            if ((double)sum == meet_point) {
                segment_number = -1;
                break;
            }
 
            // if sum is greater
            // than middle point
            if (sum > meet_point) {
                segment_number = i + 1;
                break;
            }
        }
 
        return segment_number;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int n = 13;
        int m = 3;
        int[] segment_length = new int[] { 3, 2, 8 };
 
        int ans = findSegment(n, m, segment_length);
        System.out.println(ans);
    }
}


Python3




# Python 3 implementation of the approach
 
# Function that returns the segment for the
# middle point
 
 
def findSegment(n, m, segment_length):
    # the middle point
    meet_point = (1.0 * n) / 2.0
    sum = 0
 
    # stores the segment index
    segment_number = 0
 
    for i in range(0, m, 1):
        # increment sum by
        # length of the segment
        sum += segment_length[i]
 
        # if the middle is
        # in between two segments
        if (sum == meet_point):
            segment_number = -1
            break
 
        # if sum is greater
        # than middle point
        if (sum > meet_point):
            segment_number = i + 1
            break
 
    return segment_number
 
 
# Driver code
if __name__ == '__main__':
    n = 13
    m = 3
    segment_length = [3, 2, 8]
 
    ans = findSegment(n, m, segment_length)
    print(ans)
# This code is contributed by
# Surendra_Gangwar


C#




// C# implementation of the approach
using System;
class GFG {
 
    // Function that returns the
    // segment for the middle point
    static int findSegment(int n, int m,
                           int[] segment_length)
    {
 
        // the middle point
        double meet_point = (1.0 * n) / 2.0;
        int sum = 0;
 
        // stores the segment index
        int segment_number = 0;
 
        for (int i = 0; i < m; i++) {
 
            // increment sum by
            // length of the segment
            sum += segment_length[i];
 
            // if the middle is
            // in between two segments
            if ((double)sum == meet_point) {
                segment_number = -1;
                break;
            }
 
            // if sum is greater
            // than middle point
            if (sum > meet_point) {
                segment_number = i + 1;
                break;
            }
        }
 
        return segment_number;
    }
 
    // Driver code
    public static void Main()
    {
        int n = 13;
        int m = 3;
        int[] segment_length = new int[] { 3, 2, 8 };
 
        int ans = findSegment(n, m, segment_length);
        Console.WriteLine(ans);
    }
}
 
// This code is contributed
// by shs


PHP




<?php
// PHP ementation of the approach
 
// Function that returns the segment
// for the middle point
function findSegment($n, $m,
                     $segment_length)
{
 
    // the middle point
    $meet_point = (1.0 * $n) / 2.0;
    $sum = 0;
 
    // stores the segment index
    $segment_number = 0;
 
    for ($i = 0; $i < $m; $i++)
    {
 
        // increment sum by
        // length of the segment
        $sum += $segment_length[$i];
 
        // if the middle is
        // in between two segments
        if ((double)$sum == $meet_point)
        {
            $segment_number = -1;
            break;
        }
 
        // if sum is greater
        // than middle point
        if ($sum > $meet_point)
        {
            $segment_number = $i + 1;
            break;
        }
    }
 
    return $segment_number;
}
 
// Driver code
$n = 13;
$m = 3;
$segment_length = array( 3, 2, 8 );
 
$ans = findSegment($n, $m,
                   $segment_length);
echo ($ans);
     
// This code is contributed by ajit
?>


Javascript




<script>
// Javascript implementation of the approach
 
    // Function that returns the segment for the
    // middle point
    function findSegment( n, m ,segment_length) {
 
        // the middle point
        let meet_point = (1.0 * n) / 2.0;
        let sum = 0;
 
        // stores the segment index
        let segment_number = 0, i;
 
        for ( i = 0; i < m; i++) {
 
            // increment sum by
            // length of the segment
            sum += segment_length[i];
 
            // if the middle is
            // in between two segments
            if ( sum == meet_point) {
                segment_number = -1;
                break;
            }
 
            // if sum is greater
            // than middle point
            if (sum > meet_point) {
                segment_number = i + 1;
                break;
            }
        }
        return segment_number;
    }
 
    // Driver code    
    let n = 13;
    let m = 3;
    let segment_length =[ 3, 2, 8 ];
 
    let ans = findSegment(n, m, segment_length);
    document.write(ans);
 
// This code is contributed by Rajput-Ji
</script>


Output

3

Complexity Analysis:

  • Time Complexity: O(m), for traversal
  • Auxiliary Space: O(1), as no extra space is required


Similar Reads

Find Equal (or Middle) Point in a sorted array with duplicates
Given a sorted array of n size, the task is to find whether an element exists in the array from where the number of smaller elements is equal to the number of greater elements.If Equal Point appears multiple times in input array, return the index of its first occurrence. If doesn't exist, return -1. Examples : Input : arr[] = {1, 2, 3, 3, 3, 3} Out
9 min read
Find an Integer point on a line segment with given two ends
Given two points pointU and pointV in XY-space, we need to find a point which has integer coordinates and lies on a line going through points pointU and pointV. Examples: If pointU = (1, -1 and pointV = (-4, 1) then equation of line which goes through these two points is, 2X + 5Y = -3 One point with integer co-ordinate which satisfies above equatio
8 min read
Find time required to reach point N from point 0 according to given rules
Given two positive integers X and Y and N number of points arranged in a line, the task is to find the time required to reach point N from point 0 according to the following rules: Every point has one barrier that closes after every Y minutes and remains closed for the next Y minutes.On reaching a point if the barrier is closed, then the person nee
7 min read
Shift all prefixes by given lengths
Given a string S containing letters and digits, and an integer array Shift where, [Tex]1 \leq S.length()=length(Shift) \leq 10^{5} [/Tex]and for each element of Shift array [Tex]0 \leq Shift[i] \leq 10^{9} [/Tex]. The task is, for each Shift[i] = X, you have to shift the first i+1 letters of S, X times. Return the final string after all applying al
6 min read
Number of triangles possible with given lengths of sticks which are powers of 2
Given an array of N integers where arr[i] denotes the number of sticks of length 2i. The task is to find the number of triangles possible with given lengths having area ? 0. Note: Every stick can only be used once. Examples: Input: a[] = {1, 2, 2, 2, 2} Output: 3 All possible triangles are: (20, 24, 24), (21, 23, 23), (21, 22, 22). Input: a[] = {3,
7 min read
Sum of lengths of all paths possible in a given tree
Given a tree with N nodes, the task is to find the sum of lengths of all the paths. Path length for two nodes in the tree is the number of edges on the path and for two adjacent nodes in the tree, the length of the path is 1. Examples: Input: 0 / \ 1 2 / \ 3 4 Output: 18 Paths of length 1 = (0, 1), (0, 2), (1, 3), (1, 4) = 4 Paths of length 2 = (0,
9 min read
Area of a Triangle from the given lengths of medians
Given three integers A,B and C which denotes length of the three medians of a triangle, the task is to calculate the area of the triangle. A median of a triangle is a line segment joining a vertex to the midpoint of the opposite side, thus bisecting that side. Examples: Input: A = 9, B = 12, C = 15 Output: 72.0Input: A = 39, B = 42, C = 45 Output:
4 min read
Queries to count distinct Binary Strings of all lengths from N to M satisfying given properties
Given a K and a matrix Q[][] consisting of queries of the form {N, M}, the task for each query is to count the number of strings possible of all lengths from Q[i][0] to Q[i][1] satisfying the following properties: The frequency of 0's is equal to a multiple of K.Two strings are said to be different only if the frequencies of 0's and 1's are differe
6 min read
Check if a right-angled triangle can be formed by the given side lengths
Given two positive integers A and B representing the sides of a triangle, the task is to check if the given two sides of the triangle are sides of a valid right-angled triangle or not. If found to be true, print "YES". Otherwise, print "No". Examples: Input: A = 3, B = 4Output: Yes Explanation: A right-angled triangle is possible with side lengths
8 min read
Maximize sum of averages of subsequences of lengths lying in a given range
Given an array A[] consisting of N integers and two integers X and Y, the task is to find the maximum sum of the averages of each subsequences obtained by splitting the array into subsequences of lengths lying in the range [X, Y]. Note: The values of X and Y are such that it is always possible to make such groups. Examples: Input: A[] = {4, 10, 6,
8 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg