/* VIM: let b:lcppflags="-std=c++14 -O2 -pthread -I." VIM: let b:wcppflags="/O2 /EHsc /DWIN32" */ #include #include #include #include #include #include /* snap-inc-interview-questions You are given an array of integers and a number K. You have to find the any continue sub-array whose elements sum is K. Please note that, the array may have positive, negative, and zeros as its element. The desired complexity is O(N). Example: Input: [7 0 9 -10 0 789], K = 0 Output: Array from index 1 to Index 1. Input: [1 2 3 5 -10] K = 0 Output: Array from Index 1 to Index 4. If K = -2, Output would have been SubArray from Index 2 to Index 4. */ void solution( std::vector v, int K ) { int f = -1; int l = -2; std::unordered_map m; int s = 0; for ( int i = 0; i < v.size(); ++i ) { s+= v[i]; auto p = m.emplace( s, i); if ( !p.second ){ p.first->second = i; } } s = 0; for ( int i = 0; i < v.size(); ++i ) { auto r = m.find(s+K); if ( r != m.end() && l-f < r->second - i){ l = r->second; f = i; } s+= v[i]; } std::cout << " {"; for ( auto i : v ){ std::cout << i << ", "; } std::cout << "}, " << K << " -> (" << f << ", " << l << ")" << std::endl; } int main ( void ) {try{ solution({7, 0, 9, -10, 0, 789}, 0); solution({1, 2, 3, 5, -10}, 0); solution({1, 2, 3, 5, -10}, -2); solution({1, 2, 3, 5, -10}, -10); solution({1, 2, 3, 5, -10}, 1); solution({7, 2, 9, -10, 0, 789}, 7); solution({7, 2, 9, -10, 0, 789}, 10000); return 0; } catch ( const std::exception& e ) { std::cerr << std::endl << "std::exception(\"" << e.what() << "\")." << std::endl; return 2; } catch ( ... ) { std::cerr << std::endl << "unknown exception." << std::endl; return 1; }}