• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

Pro Programming

Professional way of Programming: Learn C, C++, Java, Python, Dot Net, Android the professional way

  • Home
  • C MCQs
  • C/C++ Programs
  • Java Programs
  • C#
  • Python
  • MySQL
  • Topics
    • Arrays
    • Strings
    • Link Lists
    • Trees
    • Shapes
  • Projects
  • Articles
  • Games
You are here: Home / Archives for Partition the array into three equal sum segments

Partition the array into three equal sum segments

Repeated Character Whose First Appearance is Leftmost

Leave a Comment


Given a string, find the repeated character present first in the string.


Examples:


Input  : geeksforgeeks
Output : g
(mind that it will be g, not e.)

Input  : abcdabcd
Output : a

Input  : abcd
Output : -1
No character repeats

Asked in: Goldman Sachs internship

We have discussed different approaches in Find repeated character present first in a string.

How to solve this problem using one traversal of input string?


Method 1 (Traversing from Left to Right)
We traverse the string from left to right. We keep track of the leftmost index of every character. If a character repeats, we compare its leftmsot index with current result and update the result if result is greater

#include <bits/stdc++.h>

using namespace std;

#define NO_OF_CHARS 256

int firstRepeating(string& str)

{

int firstIndex[NO_OF_CHARS];

for (int i = 0; i < NO_OF_CHARS; i++)

firstIndex[i] = -1;

int res = INT_MAX;

for (int i = 0; i < str.length(); i++) {

if (firstIndex[str[i]] == -1)

firstIndex[str[i]] = i;

else

res = min(res, firstIndex[str[i]]);

}

return (res == INT_MAX) ? -1 : res;

}

int main()

{

string str = "geeksforgeeks";

int index = firstRepeating(str);

if (index == -1)

printf("Either all characters are "

"distinct or string is empty");

else

printf("First Repeating character"

" is %c",

str[index]);

return 0;

}

Output:


First Repeating character is g

Time Complexity : O(n). It does only one traversal of input string.
Auxiliary Space : O(1)


Method 2 (Traversing Right to Left)
We traverse the string from right to left. We keep track of the visited characters. If a character repeats, we update the result.

#include <bits/stdc++.h>

using namespace std;

#define NO_OF_CHARS 256

int firstRepeating(string& str)

{

bool visited[NO_OF_CHARS];

for (int i = 0; i < NO_OF_CHARS; i++)

visited[i] = false;

int res = -1;

for (int i = str.length() - 1; i >= 0; i--) {

if (visited[str[i]] == false)

visited[str[i]] = true;

else

res = i;

}

return res;

}

int main()

{

string str = "geeksforgeeks";

int index = firstRepeating(str);

if (index == -1)

printf("Either all characters are "

"distinct or string is empty");

else

printf("First Repeating character"

" is %c",

str[index]);

return 0;

}

Output:


First Repeating character is g

Time Complexity : O(n). It does only one traversal of input string.
Auxiliary Space : O(1)

The method 2 is better than method 1 as it does fewer comparisons.




If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the “Improve Article” button below.

Article Tags :


thumb_up
1

Please write to us at [email protected] to report any issue with the above content.


Post navigation


Previous

first_page Minimum number of pairs required to make two strings same







Source link

Filed Under: c programming Tagged With: •   Dynamic Programming, About Us, Advanced Data Structure, Advanced Topics, Algo ▼, Algorithm Paradigms ►, Algorithms, All Algorithms, All Data Structures, Analysis of Algorithms, Aptitude, Array, Backtracking, Binary Search Tree, Binary Tree, Bit Algorithms, Branch & Bound, C, Campus Ambassador Program, Campus Geek of the Month, Careers, Check for balanced parentheses in Python, Check if array can be sorted with one swap, Check if frequency of character in one string is a factor or multiple of frequency of same character in other string, Check if it is possible to reach a number by making jumps of two given length, Company Prep, Company-wise, Competitive Programming, Compiler Design, Computer Graphics, Computer Networks, Computer Organization, Computer Organization & Architecture, Contact Us, Contests, contribute.geeksforgeeks.org, contributed articles, Core Subjects ►, Count common characters in two strings, Count numbers < = N whose difference with the count of primes upto them is > = K, Count occurrences of a character in a repeated string, Count of strings that become equal to one of the two strings after one removal, Count substrings that starts with character X and ends with character Y, Count the number of operations required to reduce the given number, Count Triplets such that one of the numbers can be written as sum of the other two, Courses, Coviam Software Developer Internship Experience, CS Subjects, CS Subjects ▼, CS Subjectwise ►, CSS, Data Structures, DBMS, Design Patterns, Digital Electronics, Divide and Conquer, Divide array into two parts with equal sum according to the given constraints, DS ▼, Efficiently find first repeated character in a string without using any additional data structure in one traversal, Engg. Mathematics, Experienced Interviews, Find a distinct pair (x, Find a string such that every character is lexicographically greater than its immediate next character, Find maximum N such that the sum of square of first N natural numbers is not more than X, Find maximum sum taking every Kth element in the array, Find minimum positive integer x such that a(x^2) + b(x) + c >= k, Find missing element in a sorted array of consecutive numbers, Find repeated character present first in a string, Find the first repeated character in a string, find the kth largest element in the range [l, find the kth sub-string when all the sub-strings are sorted according to the given condition, Find the minimum number of rectangles left after inserting one into another, Find the number of elements greater than k in a sorted array, Game Theory, GATE ▼, GATE 2019, GATE CS Corner, GATE Notes, GATE Official Papers, GBlog, Geek of the Month, Geek on the Top, Geometric Algorithms, Given a string and an integer k, Given an array and two integers l and r, Goldman Sachs, Graph, Graph Algorithms, Greedy Algorithms, Group all occurrences of characters according to first appearance, Hashing, Heap, HTML, HTML & XML, ide.geeksforgeeks.org, Integers from the range that are composed of a single distinct digit, Internship, Internship Interviews, Internships, Interview ▼, Interview Experiences, ISRO CS Exam, Java, Java Program to print distinct permutations of a string, JavaScript, jQuery, Languages, Languages ►, Languages ▼, Last Minute Notes, Leftmost and rightmost indices of the maximum and the minimum element of an array, LinkedList, Longest Common Prefix using Character by Character Matching, Machine Learning, MakeMyTrip Interview Experience 2019, Mathematical Algorithms, Matrix, Maximum element in a sorted and rotated array, Microprocessor, Minimize the maximum minimum difference after one removal from array, Minimum in an array which is first decreasing then increasing, Minimum number of pairs required to make two strings same, Multiple Choice Quizzes, Nagarro Interview Experience Off-campus, Number of subarrays have bitwise OR >= K, Occurrences of a pattern in binary representation of a number, Operating Systems, Pairs with same Manhattan and Euclidean distance, Partition the array into three equal sum segments, Pattern Searching, Persistent Trie | Set 1 (Introduction), PHP, Placement Course, Practice, Practice Company Questions, Print all permutations of a string in Java, Privacy Policy, Program Output, Project, Puzzles, Python, Queue, Quizzes ▼, r], Randomized Algorithms, Recommended: Please try your approach on, Remove all occurrences of any element for maximum array sum, Remove exactly one element from the array such that max - min is minimum, Repeated subsequence of length 2 or more, Replace every character of a string by a different character, Replace every character of string by character whose ASCII value is K times more than it, Scala, School Programming, Search an element in given N ranges, Search element in a Spirally sorted Matrix, Searching, Searching Algorithms, Second most repeated word in a sequence, Shortest distance to every other character from given character, Skip to content, Smallest Pair Sum in an array, Software Engineering, Some rights reserved, Sorting Algorithms, SQL, Stack, Strings, Students ▼, Subjective Questions, Suggest an Article, Ternary Search, Testimonials, Theory of Computation, Top Topics, Topic-wise, Topicwise ►, Tree based DS ►, Two equal sum segment range queries, UGC NET CS Paper II, UGC NET CS Paper III, UGC NET Papers, Video Tutorials, Videos, Web Technology, What’s Difference?, Write an Article, Write Interview Experience, y) in given range such that x divides y

Maximum volume of cube for every person when edge of N cubes are given

Leave a Comment


Given an array of N integers which denotes the edges of N cubical structures respectively. Also given are M integers which denotes the number of peoples. The task is to find the maximum amount of volume of a cube that can be given to every person.

Note: Cubes can be cut of any shape from any of the N cubes.

Examples:

Input: a[] = {1, 1, 1, 2, 2}, m = 3
Output: 4
All three person get a slice of volume 4 each
Person 1 gets a slice of volume 4 from the last cube.
Person 2 gets a slice of volume 4 from the last cube.
Person 3 gets a slice of volume 4 from the second last cube.

Input: a[] = {2, 2, 2, 2, 2}, m = 4
Output: 8


Naive Approach: A naive approach is to first calculate the volume of all of the cubes and then linearly check for every volume that it can be distributed among all M people or not and find the maximum volume among all such volumes.

Time Complexity: O(N2)

Efficient Approach: An efficient approach is to use binary search to find the answer. Since the edge lengths are given in the array, convert them to the volume of the respective cubes.

Find the maximum volume among volumes of all of the cubes. Say, the maximum volume is maxVolume. Now, perform binary search on the range [0, maxVolume].

  • Calculate the middle value of the range, say mid.
  • Now, calculate the total number of cubes that can be cut of all of the cubes of volume mid.
  • If the total cubes that can be cut exceed the number of persons, then that amount of volume of cubes can be cut for every person, hence we check for a larger value in the range [mid+1, maxVolume].
  • If the total cubes do not exceed the number of persons, then we check for an answer in the range [low, mid-1].

Below is the implementation of the above approach:

#include <bits/stdc++.h>

using namespace std;

int getMaximumVloume(int a[], int n, int m)

{

int maxVolume = 0;

for (int i = 0; i < n; i++) {

a[i] = a[i] * a[i] * a[i];

maxVolume = max(a[i], maxVolume);

}

int low = 0, high = maxVolume;

int maxVol = 0;

while (low <= high) {

int mid = (low + high) >> 1;

int cnt = 0;

for (int i = 0; i < n; i++) {

cnt += a[i] / mid;

}

if (cnt >= m) {

low = mid + 1;

maxVol = max(maxVol, mid);

}

else

high = mid - 1;

}

return maxVol;

}

int main()

{

int a[] = { 1, 1, 1, 2, 2 };

int n = sizeof(a) / sizeof(a[0]);

int m = 3;

cout << getMaximumVloume(a, n, m);

return 0;

}

Time Complexity: O(N * log (maxVolume))



Striver(underscore)79 at Codechef and codeforces D


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the “Improve Article” button below.

Article Tags :


thumb_up
Be the First to upvote.

Please write to us at [email protected] to report any issue with the above content.


Post navigation


Previous

first_page Partition the array into three equal sum segments







Source link

Filed Under: c programming Tagged With: •   Dynamic Programming, About Us, Advanced Data Structure, Advanced Topics, Algo ▼, Algorithm Paradigms ►, Algorithms, All Algorithms, All Data Structures, Analysis of Algorithms, Aptitude, Array, Array Manipulation and Sum, Arrays, Backtracking, Binary Search, Binary Search Tree, Binary Tree, Bit Algorithms, Branch & Bound, C, Calculate the total fine to be collected, Campus Ambassador Program, Campus Geek of the Month, Careers, Check if an array is sorted and rotated, Check if X can give change to every person in the Queue, Check whether an Array is Subarray of another Array, Coin game of two corners (Greedy Approach), Company Prep, Company-wise, Competitive Programming, Compiler Design, Computer Graphics, Computer Networks, Computer Organization, Computer Organization & Architecture, Constructive Algorithms, Contact Us, Contests, contribute.geeksforgeeks.org, Convert a String to Integer Array in C/C++, Core Subjects ►, Count array elements that divide the sum of all other elements, Count distinct elements in an array, Count of pairs (x, Courses, Coviam Software Developer Internship Experience, CS Subjects, CS Subjects ▼, CS Subjectwise ►, CSS, Data Structures, DBMS, Design a Hit Counter, Design Patterns, Digital Electronics, Divide and Conquer, DS ▼, Engg. Mathematics, Experienced Interviews, Find triplets in an array whose AND is maximum, Find two numbers whose divisors are given in a random order, For each element in 1st array count elements less than or equal to it in 2nd array | Set 2, Game Theory, GATE ▼, GATE 2019, GATE CS Corner, GATE Notes, GATE Official Papers, GBlog, Geek of the Month, Geek on the Top, Generating subarrays using recursion, Geometric Algorithms, Graph, Graph Algorithms, Greedy Algorithms, Hashing, Heap, How do Dynamic arrays work?, HTML, HTML & XML, ide.geeksforgeeks.org, Internship, Internship Interviews, Internships, Interview ▼, Interview Experiences, ISRO CS Exam, Java, JavaScript, jQuery, K maximum sum combinations from two arrays, Languages, Languages ►, Languages ▼, Largest number in an array that is not a perfect cube, Largest palindromic number in an array, Largest perfect cube number in an Array, Last Minute Notes, Length of the longest alternating subarray, Length of the longest Subarray with only Even Elements, LinkedList, Longest subarray having maximum sum, Longest subsequence such that adjacent elements have at least one common digit, Machine Learning, Make all numbers of an array equal, MakeMyTrip Interview Experience 2019, Mathematical Algorithms, Matrix, Maximum even sum subsequence, Maximum length of rod for Q-th person, Maximum Sum Path in Two Arrays, Maximum sum rectangle in a 2D matrix | DP-27, Maximum triplet sum in array, Maximum value of |arr[0] - arr[1]| + |arr[1] - arr[2]| + ... +|arr[n - 2] - arr[n - 1]| when elements are from 1 to n, Maximum value of |arr[i] - arr[j]| + |i - j|, Maximum value of arr[i] % arr[j] for a given array, Merge K sorted arrays | Set 3 ( Using Divide and Conquer Approach ), Microprocessor, Minimum elements to be removed such that sum of adjacent elements is always even, Minimum number of items to be delivered, Minimum number of swaps required to sort an array | Set 2, Minimum operations required to make all the array elements equal, Multidimensional Arrays in Java, Multiple Choice Quizzes, Next greater element in same order as input, Operating Systems, Partition the array into three equal sum segments, Pattern Searching, PHP, Placement Course, Practice, Practice Company Questions, Privacy Policy, Program for K Most Recently Used (MRU) Apps, Program Output, Program to check if an array is palindrome or not using Recursion, Program to find the Hidden Number, Project, Puzzles, Python, Queue, Quizzes ▼, Randomized Algorithms, Reach the numbers by making jumps of two given lengths, Rearrange Odd and Even values in Alternate Fashion in Ascending Order, Remove duplicates from unsorted array, School Programming, Searching Algorithms, Skip to content, Sliding Window Maximum (Maximum of all subarrays of size k), Smallest perfect Cube divisible by all elements of an array, Software Engineering, Some rights reserved, Sort elements by frequency | Set 5 (using Java Map), Sorting Algorithms, SQL, Stack, Strings, Students ▼, Subjective Questions, Subsequence with maximum odd sum, Suggest an Article, Sum of all odd frequency elements in an array, Sum of minimum elements of all subarrays, Sum of XOR of all subarrays, Testimonials, Theory of Computation, Top Topics, Topic-wise, Topicwise ►, Tree based DS ►, UGC NET CS Paper II, UGC NET CS Paper III, UGC NET Papers, Video Tutorials, Videos, Web Technology, What’s Difference?, Write an Article, Write Interview Experience, y) in an array such that x < y

Primary Sidebar

Recent Posts

  • Surveying Questions and Answers – Airport Survey
  • A list of top 10 Cryptocurrencies
  • Indus Valley Partners Interview Experience- Aug(2019) On Campus
  • Surveying Questions and Answers – Tunnelling
  • 9r. WebDriver – Assert and Verify
  • Privacy Policy
  • About
  • Contact US

© 2019 ProProgramming
 Privacy Policy About Contact Us