Ecoer Logo
VOTING POWER100.00%
DOWNVOTE POWER100.00%
RESOURCE CREDITS100.00%
REPUTATION PROGRESS4.12%
Net Worth
0.097USD
STEEM
0.443STEEM
SBD
0.079SBD
Effective Power
5.001SP
├── Own SP
0.629SP
└── Incoming Deleg
+4.372SP

Detailed Balance

STEEM
balance
0.004STEEM
market_balance
0.000STEEM
savings_balance
0.000STEEM
reward_steem_balance
0.439STEEM
STEEM POWER
Own SP
0.629SP
Delegated Out
0.000SP
Delegation In
4.372SP
Effective Power
5.001SP
Reward SP (pending)
0.471SP
SBD
sbd_balance
0.000SBD
sbd_conversions
0.000SBD
sbd_market_balance
0.000SBD
savings_sbd_balance
0.000SBD
reward_sbd_balance
0.079SBD
{
  "balance": "0.004 STEEM",
  "savings_balance": "0.000 STEEM",
  "reward_steem_balance": "0.439 STEEM",
  "vesting_shares": "1024.680389 VESTS",
  "delegated_vesting_shares": "0.000000 VESTS",
  "received_vesting_shares": "7118.979417 VESTS",
  "sbd_balance": "0.000 SBD",
  "savings_sbd_balance": "0.000 SBD",
  "reward_sbd_balance": "0.079 SBD",
  "conversions": []
}

Account Info

namegolibrary
id539644
rank1,315,816
reputation21772606377
created2017-12-30T05:37:00
recovery_accountsteem
proxyNone
post_count21
comment_count0
lifetime_vote_count0
witnesses_voted_for0
last_post2020-03-28T13:27:57
last_root_post2020-03-28T13:27:57
last_vote_time2020-03-21T04:18:00
proxied_vsf_votes0, 0, 0, 0
can_vote1
voting_power0
delayed_votes0
balance0.004 STEEM
savings_balance0.000 STEEM
sbd_balance0.000 SBD
savings_sbd_balance0.000 SBD
vesting_shares1024.680389 VESTS
delegated_vesting_shares0.000000 VESTS
received_vesting_shares7118.979417 VESTS
reward_vesting_balance925.230393 VESTS
vesting_balance0.000 STEEM
vesting_withdraw_rate0.000000 VESTS
next_vesting_withdrawal1969-12-31T23:59:59
withdrawn0
to_withdraw0
withdraw_routes0
savings_withdraw_requests0
last_account_recovery1970-01-01T00:00:00
reset_accountnull
last_owner_update1970-01-01T00:00:00
last_account_update1970-01-01T00:00:00
minedNo
sbd_seconds0
sbd_last_interest_payment1970-01-01T00:00:00
savings_sbd_last_interest_payment1970-01-01T00:00:00
{
  "active": {
    "account_auths": [],
    "key_auths": [
      [
        "STM8JhXzxDn1wknU8wfgsUhu2kUh8jJm9Y6NYAGKcY3B3TQ5uhBUJ",
        1
      ]
    ],
    "weight_threshold": 1
  },
  "balance": "0.004 STEEM",
  "can_vote": true,
  "comment_count": 0,
  "created": "2017-12-30T05:37:00",
  "curation_rewards": 0,
  "delegated_vesting_shares": "0.000000 VESTS",
  "downvote_manabar": {
    "current_mana": 2035914951,
    "last_update_time": 1779065130
  },
  "guest_bloggers": [],
  "id": 539644,
  "json_metadata": "",
  "last_account_recovery": "1970-01-01T00:00:00",
  "last_account_update": "1970-01-01T00:00:00",
  "last_owner_update": "1970-01-01T00:00:00",
  "last_post": "2020-03-28T13:27:57",
  "last_root_post": "2020-03-28T13:27:57",
  "last_vote_time": "2020-03-21T04:18:00",
  "lifetime_vote_count": 0,
  "market_history": [],
  "memo_key": "STM7GJE6AoQW45SSmqFQh4xinJhz4wk9UJozxW1mto34nrRakVC8Y",
  "mined": false,
  "name": "golibrary",
  "next_vesting_withdrawal": "1969-12-31T23:59:59",
  "other_history": [],
  "owner": {
    "account_auths": [],
    "key_auths": [
      [
        "STM8FP7i1oJrYAkUbLzWnvTdt96veEd6enUVG6GW4VhVDyqMwVuK7",
        1
      ]
    ],
    "weight_threshold": 1
  },
  "pending_claimed_accounts": 0,
  "post_bandwidth": 0,
  "post_count": 21,
  "post_history": [],
  "posting": {
    "account_auths": [],
    "key_auths": [
      [
        "STM7rCjZzdVTP2mtB59XXofgqFxLimUmsEgx56cYvU949CJxGi54g",
        1
      ]
    ],
    "weight_threshold": 1
  },
  "posting_json_metadata": "",
  "posting_rewards": 632,
  "proxied_vsf_votes": [
    0,
    0,
    0,
    0
  ],
  "proxy": "",
  "received_vesting_shares": "7118.979417 VESTS",
  "recovery_account": "steem",
  "reputation": "21772606377",
  "reset_account": "null",
  "reward_sbd_balance": "0.079 SBD",
  "reward_steem_balance": "0.439 STEEM",
  "reward_vesting_balance": "925.230393 VESTS",
  "reward_vesting_steem": "0.471 STEEM",
  "savings_balance": "0.000 STEEM",
  "savings_sbd_balance": "0.000 SBD",
  "savings_sbd_last_interest_payment": "1970-01-01T00:00:00",
  "savings_sbd_seconds": "0",
  "savings_sbd_seconds_last_update": "1970-01-01T00:00:00",
  "savings_withdraw_requests": 0,
  "sbd_balance": "0.000 SBD",
  "sbd_last_interest_payment": "1970-01-01T00:00:00",
  "sbd_seconds": "0",
  "sbd_seconds_last_update": "1970-01-01T00:00:00",
  "tags_usage": [],
  "to_withdraw": 0,
  "transfer_history": [],
  "vesting_balance": "0.000 STEEM",
  "vesting_shares": "1024.680389 VESTS",
  "vesting_withdraw_rate": "0.000000 VESTS",
  "vote_history": [],
  "voting_manabar": {
    "current_mana": "8143659806",
    "last_update_time": 1779065130
  },
  "voting_power": 0,
  "withdraw_routes": 0,
  "withdrawn": 0,
  "witness_votes": [],
  "witnesses_voted_for": 0,
  "rank": 1315816
}

Withdraw Routes

IncomingOutgoing
Empty
Empty
{
  "incoming": [],
  "outgoing": []
}
From Date
To Date
steemdelegated 4.372 SP to @golibrary
2026/05/18 00:45:30
delegatorsteem
delegateegolibrary
vesting shares7118.979417 VESTS
Transaction InfoBlock #106144052/Trx 0b581cac9aac2f1daf111e70dc78ee27abb47f9d
View Raw JSON Data
{
  "trx_id": "0b581cac9aac2f1daf111e70dc78ee27abb47f9d",
  "block": 106144052,
  "trx_in_block": 0,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2026-05-18T00:45:30",
  "op": [
    "delegate_vesting_shares",
    {
      "delegator": "steem",
      "delegatee": "golibrary",
      "vesting_shares": "7118.979417 VESTS"
    }
  ]
}
steemdelegated 2.706 SP to @golibrary
2026/05/12 05:54:00
delegatorsteem
delegateegolibrary
vesting shares4406.769012 VESTS
Transaction InfoBlock #105978176/Trx 678c15ac5976c05759f69eaa59b3b2d1767a9eb9
View Raw JSON Data
{
  "trx_id": "678c15ac5976c05759f69eaa59b3b2d1767a9eb9",
  "block": 105978176,
  "trx_in_block": 0,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2026-05-12T05:54:00",
  "op": [
    "delegate_vesting_shares",
    {
      "delegator": "steem",
      "delegatee": "golibrary",
      "vesting_shares": "4406.769012 VESTS"
    }
  ]
}
steemdelegated 4.380 SP to @golibrary
2026/04/26 00:05:39
delegatorsteem
delegateegolibrary
vesting shares7131.495173 VESTS
Transaction InfoBlock #105511691/Trx 35a00662bf737dd0beeed686b0ffe4bded8881a5
View Raw JSON Data
{
  "trx_id": "35a00662bf737dd0beeed686b0ffe4bded8881a5",
  "block": 105511691,
  "trx_in_block": 0,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2026-04-26T00:05:39",
  "op": [
    "delegate_vesting_shares",
    {
      "delegator": "steem",
      "delegatee": "golibrary",
      "vesting_shares": "7131.495173 VESTS"
    }
  ]
}
steemdelegated 2.732 SP to @golibrary
2026/01/23 09:09:27
delegatorsteem
delegateegolibrary
vesting shares4448.315831 VESTS
Transaction InfoBlock #102853435/Trx 90c9c1e50171d515bbf60af961c48d175f58d355
View Raw JSON Data
{
  "trx_id": "90c9c1e50171d515bbf60af961c48d175f58d355",
  "block": 102853435,
  "trx_in_block": 0,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2026-01-23T09:09:27",
  "op": [
    "delegate_vesting_shares",
    {
      "delegator": "steem",
      "delegatee": "golibrary",
      "vesting_shares": "4448.315831 VESTS"
    }
  ]
}
2025/01/19 00:00:39
parent authorgolibrary
parent permlinkhistoryofunixandlinux-mhf7yno5g3
authorcaymancrypto
permlinksqb6p2
title
bodyYou might like to learn about [MINiX](https://bsky.app/profile/newblicious.bsky.social/post/3lg2hbbuwk22a) #linux
json metadata{"tags":["linux"],"links":["https://bsky.app/profile/newblicious.bsky.social/post/3lg2hbbuwk22a"],"app":"steemit/0.2"}
Transaction InfoBlock #92242624/Trx dca74597280589ee5205c94a76cf6e69fa9c959b
View Raw JSON Data
{
  "trx_id": "dca74597280589ee5205c94a76cf6e69fa9c959b",
  "block": 92242624,
  "trx_in_block": 0,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2025-01-19T00:00:39",
  "op": [
    "comment",
    {
      "parent_author": "golibrary",
      "parent_permlink": "historyofunixandlinux-mhf7yno5g3",
      "author": "caymancrypto",
      "permlink": "sqb6p2",
      "title": "",
      "body": "You might like to learn about [MINiX](https://bsky.app/profile/newblicious.bsky.social/post/3lg2hbbuwk22a)\n\n#linux",
      "json_metadata": "{\"tags\":[\"linux\"],\"links\":[\"https://bsky.app/profile/newblicious.bsky.social/post/3lg2hbbuwk22a\"],\"app\":\"steemit/0.2\"}"
    }
  ]
}
steemdelegated 2.833 SP to @golibrary
2024/12/17 04:27:57
delegatorsteem
delegateegolibrary
vesting shares4612.535028 VESTS
Transaction InfoBlock #91299828/Trx ef3f8d03032668a5ff2ecd760245b38f620f5860
View Raw JSON Data
{
  "trx_id": "ef3f8d03032668a5ff2ecd760245b38f620f5860",
  "block": 91299828,
  "trx_in_block": 4,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2024-12-17T04:27:57",
  "op": [
    "delegate_vesting_shares",
    {
      "delegator": "steem",
      "delegatee": "golibrary",
      "vesting_shares": "4612.535028 VESTS"
    }
  ]
}
steemdelegated 2.936 SP to @golibrary
2023/11/13 20:11:00
delegatorsteem
delegateegolibrary
vesting shares4781.668560 VESTS
Transaction InfoBlock #79854031/Trx 97374437fe30ee50193c0dd0b0c5d107c443c9d8
View Raw JSON Data
{
  "trx_id": "97374437fe30ee50193c0dd0b0c5d107c443c9d8",
  "block": 79854031,
  "trx_in_block": 1,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2023-11-13T20:11:00",
  "op": [
    "delegate_vesting_shares",
    {
      "delegator": "steem",
      "delegatee": "golibrary",
      "vesting_shares": "4781.668560 VESTS"
    }
  ]
}
steemdelegated 4.740 SP to @golibrary
2023/09/21 22:25:27
delegatorsteem
delegateegolibrary
vesting shares7718.947346 VESTS
Transaction InfoBlock #78348539/Trx c349aa1e97f39409537c44980cdda9de794786ec
View Raw JSON Data
{
  "trx_id": "c349aa1e97f39409537c44980cdda9de794786ec",
  "block": 78348539,
  "trx_in_block": 8,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2023-09-21T22:25:27",
  "op": [
    "delegate_vesting_shares",
    {
      "delegator": "steem",
      "delegatee": "golibrary",
      "vesting_shares": "7718.947346 VESTS"
    }
  ]
}
steemdelegated 4.876 SP to @golibrary
2022/11/03 12:08:24
delegatorsteem
delegateegolibrary
vesting shares7940.628784 VESTS
Transaction InfoBlock #69113784/Trx c1f7257c6d5e12ab3679e8791502a733a4c4c91e
View Raw JSON Data
{
  "trx_id": "c1f7257c6d5e12ab3679e8791502a733a4c4c91e",
  "block": 69113784,
  "trx_in_block": 6,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2022-11-03T12:08:24",
  "op": [
    "delegate_vesting_shares",
    {
      "delegator": "steem",
      "delegatee": "golibrary",
      "vesting_shares": "7940.628784 VESTS"
    }
  ]
}
steemdelegated 5.012 SP to @golibrary
2022/01/17 11:22:21
delegatorsteem
delegateegolibrary
vesting shares8161.162015 VESTS
Transaction InfoBlock #60809911/Trx 6cb0db46a4d56b3ad826a2cb2d3a5aa42c914e95
View Raw JSON Data
{
  "trx_id": "6cb0db46a4d56b3ad826a2cb2d3a5aa42c914e95",
  "block": 60809911,
  "trx_in_block": 1,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2022-01-17T11:22:21",
  "op": [
    "delegate_vesting_shares",
    {
      "delegator": "steem",
      "delegatee": "golibrary",
      "vesting_shares": "8161.162015 VESTS"
    }
  ]
}
steemdelegated 5.125 SP to @golibrary
2021/06/14 01:16:30
delegatorsteem
delegateegolibrary
vesting shares8344.930673 VESTS
Transaction InfoBlock #54608275/Trx 639c18d1180988fdeeac99c27008f8e1ca998d1b
View Raw JSON Data
{
  "trx_id": "639c18d1180988fdeeac99c27008f8e1ca998d1b",
  "block": 54608275,
  "trx_in_block": 4,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2021-06-14T01:16:30",
  "op": [
    "delegate_vesting_shares",
    {
      "delegator": "steem",
      "delegatee": "golibrary",
      "vesting_shares": "8344.930673 VESTS"
    }
  ]
}
blurtofficialsent 0.001 STEEM to @golibrary- "CONGRATS! You have a 1:1 BLURT AIRDROP of 1.351 BLURT and 0.524000 BLURT POWER waiting for you. Check out https://blurtwallet.com/@golibrary and https://blurt.blog/ TODAY!"
2020/12/16 16:31:24
fromblurtofficial
togolibrary
amount0.001 STEEM
memoCONGRATS! You have a 1:1 BLURT AIRDROP of 1.351 BLURT and 0.524000 BLURT POWER waiting for you. Check out https://blurtwallet.com/@golibrary and https://blurt.blog/ TODAY!
Transaction InfoBlock #49502941/Trx 17db359564c9fcf4c15725fd38d3873779bf5ead
View Raw JSON Data
{
  "trx_id": "17db359564c9fcf4c15725fd38d3873779bf5ead",
  "block": 49502941,
  "trx_in_block": 3,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-12-16T16:31:24",
  "op": [
    "transfer",
    {
      "from": "blurtofficial",
      "to": "golibrary",
      "amount": "0.001 STEEM",
      "memo": "CONGRATS! You have a 1:1 BLURT AIRDROP of 1.351 BLURT and 0.524000 BLURT POWER waiting for you. Check out https://blurtwallet.com/@golibrary and https://blurt.blog/ TODAY!"
    }
  ]
}
steemdelegated 5.240 SP to @golibrary
2020/12/11 11:34:30
delegatorsteem
delegateegolibrary
vesting shares8532.352647 VESTS
Transaction InfoBlock #49355711/Trx f7e4ea73fd428fe419743826698177b748772273
View Raw JSON Data
{
  "trx_id": "f7e4ea73fd428fe419743826698177b748772273",
  "block": 49355711,
  "trx_in_block": 7,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-12-11T11:34:30",
  "op": [
    "delegate_vesting_shares",
    {
      "delegator": "steem",
      "delegatee": "golibrary",
      "vesting_shares": "8532.352647 VESTS"
    }
  ]
}
steemdelegated 1.175 SP to @golibrary
2020/12/06 05:11:39
delegatorsteem
delegateegolibrary
vesting shares1912.543513 VESTS
Transaction InfoBlock #49207273/Trx 9dbe97d64aeb8ab5e650b179e97ea19d38dbd990
View Raw JSON Data
{
  "trx_id": "9dbe97d64aeb8ab5e650b179e97ea19d38dbd990",
  "block": 49207273,
  "trx_in_block": 3,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-12-06T05:11:39",
  "op": [
    "delegate_vesting_shares",
    {
      "delegator": "steem",
      "delegatee": "golibrary",
      "vesting_shares": "1912.543513 VESTS"
    }
  ]
}
steemdelegated 5.244 SP to @golibrary
2020/12/05 15:12:33
delegatorsteem
delegateegolibrary
vesting shares8538.560501 VESTS
Transaction InfoBlock #49190805/Trx 32a02b2ffa71e3283df69cb028279804087a91c5
View Raw JSON Data
{
  "trx_id": "32a02b2ffa71e3283df69cb028279804087a91c5",
  "block": 49190805,
  "trx_in_block": 0,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-12-05T15:12:33",
  "op": [
    "delegate_vesting_shares",
    {
      "delegator": "steem",
      "delegatee": "golibrary",
      "vesting_shares": "8538.560501 VESTS"
    }
  ]
}
steemdelegated 1.179 SP to @golibrary
2020/11/02 16:34:36
delegatorsteem
delegateegolibrary
vesting shares1920.017158 VESTS
Transaction InfoBlock #48258905/Trx 38ebfbbd9d12823e181a7527ad0755b9b525c8e0
View Raw JSON Data
{
  "trx_id": "38ebfbbd9d12823e181a7527ad0755b9b525c8e0",
  "block": 48258905,
  "trx_in_block": 1,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-11-02T16:34:36",
  "op": [
    "delegate_vesting_shares",
    {
      "delegator": "steem",
      "delegatee": "golibrary",
      "vesting_shares": "1920.017158 VESTS"
    }
  ]
}
steemdelegated 5.346 SP to @golibrary
2020/06/27 13:31:18
delegatorsteem
delegateegolibrary
vesting shares8704.495971 VESTS
Transaction InfoBlock #44614185/Trx fcce86bd4bb58b8ff4298d9aa1ed7d61f99c260d
View Raw JSON Data
{
  "trx_id": "fcce86bd4bb58b8ff4298d9aa1ed7d61f99c260d",
  "block": 44614185,
  "trx_in_block": 4,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-06-27T13:31:18",
  "op": [
    "delegate_vesting_shares",
    {
      "delegator": "steem",
      "delegatee": "golibrary",
      "vesting_shares": "8704.495971 VESTS"
    }
  ]
}
crypto.piotrsent 0.002 STEEM to @golibrary- "Dear @golibrary, I hope you don't mind this little memo. I would like to introduce you to new "LEARN AND EARN" initiative which I came up together with @hardaeborla. Check out my latest post and hopef..."
2020/05/14 17:26:15
fromcrypto.piotr
togolibrary
amount0.002 STEEM
memoDear @golibrary, I hope you don't mind this little memo. I would like to introduce you to new "LEARN AND EARN" initiative which I came up together with @hardaeborla. Check out my latest post and hopefully you will enjoy our new idea. Obviously I would appreciate every resteem and your feedback. I read all comments. Yours, Piotr // LINK: https://steemit.com/hive-175254/@crypto.piotr/learn-and-earn-our-project-hope-new-awesome-initiative
Transaction InfoBlock #43371490/Trx a6e3eec22f95aba450468a673ab37148dc64176f
View Raw JSON Data
{
  "trx_id": "a6e3eec22f95aba450468a673ab37148dc64176f",
  "block": 43371490,
  "trx_in_block": 10,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-05-14T17:26:15",
  "op": [
    "transfer",
    {
      "from": "crypto.piotr",
      "to": "golibrary",
      "amount": "0.002 STEEM",
      "memo": "Dear @golibrary, I hope you don't mind this little memo. I would like to introduce you to new \"LEARN AND EARN\" initiative which I came up together with @hardaeborla. Check out my latest post and hopefully you will enjoy our new idea. Obviously I would appreciate every resteem and your feedback. I read all comments. Yours, Piotr // LINK: https://steemit.com/hive-175254/@crypto.piotr/learn-and-earn-our-project-hope-new-awesome-initiative"
    }
  ]
}
steemdelegated 17.678 SP to @golibrary
2020/05/09 06:09:30
delegatorsteem
delegateegolibrary
vesting shares28785.798553 VESTS
Transaction InfoBlock #43217529/Trx 8459734ad6dfde1e32807a42862153a39ddd5d77
View Raw JSON Data
{
  "trx_id": "8459734ad6dfde1e32807a42862153a39ddd5d77",
  "block": 43217529,
  "trx_in_block": 10,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-05-09T06:09:30",
  "op": [
    "delegate_vesting_shares",
    {
      "delegator": "steem",
      "delegatee": "golibrary",
      "vesting_shares": "28785.798553 VESTS"
    }
  ]
}
steemdelegated 3.284 SP to @golibrary
2020/05/08 09:49:54
delegatorsteem
delegateegolibrary
vesting shares5347.593227 VESTS
Transaction InfoBlock #43193706/Trx d36daf002f5abd5acd70c04ee14ee212bcf7de44
View Raw JSON Data
{
  "trx_id": "d36daf002f5abd5acd70c04ee14ee212bcf7de44",
  "block": 43193706,
  "trx_in_block": 5,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-05-08T09:49:54",
  "op": [
    "delegate_vesting_shares",
    {
      "delegator": "steem",
      "delegatee": "golibrary",
      "vesting_shares": "5347.593227 VESTS"
    }
  ]
}
golibraryreceived 0.149 STEEM, 0.180 SP author reward for @golibrary / squaring-a-sorted-array
2020/04/03 11:37:54
authorgolibrary
permlinksquaring-a-sorted-array
sbd payout0.000 SBD
steem payout0.149 STEEM
vesting payout293.568761 VESTS
Transaction InfoBlock #42213224/Virtual Operation #3
View Raw JSON Data
{
  "trx_id": "0000000000000000000000000000000000000000",
  "block": 42213224,
  "trx_in_block": 4294967295,
  "op_in_trx": 0,
  "virtual_op": 3,
  "timestamp": "2020-04-03T11:37:54",
  "op": [
    "author_reward",
    {
      "author": "golibrary",
      "permlink": "squaring-a-sorted-array",
      "sbd_payout": "0.000 SBD",
      "steem_payout": "0.149 STEEM",
      "vesting_payout": "293.568761 VESTS"
    }
  ]
}
golibraryreceived 0.184 SP benefactor reward from @remlaps-lite
2020/03/29 15:56:00
benefactorgolibrary
authorremlaps-lite
permlinkcurating-the-internet-science-and-technology-digest-for-march-22-2020
sbd payout0.000 SBD
steem payout0.153 STEEM
vesting payout299.513643 VESTS
Transaction InfoBlock #42076413/Virtual Operation #33
View Raw JSON Data
{
  "trx_id": "0000000000000000000000000000000000000000",
  "block": 42076413,
  "trx_in_block": 4294967295,
  "op_in_trx": 0,
  "virtual_op": 33,
  "timestamp": "2020-03-29T15:56:00",
  "op": [
    "comment_benefactor_reward",
    {
      "benefactor": "golibrary",
      "author": "remlaps-lite",
      "permlink": "curating-the-internet-science-and-technology-digest-for-march-22-2020",
      "sbd_payout": "0.000 SBD",
      "steem_payout": "0.153 STEEM",
      "vesting_payout": "299.513643 VESTS"
    }
  ]
}
golibrarycustom json: follow
2020/03/29 11:37:48
required auths[]
required posting auths["golibrary"]
idfollow
json["reblog",{"account":"golibrary","author":"golibrary","permlink":"find-all-triplets-with-sum-zero-in-a-given-array"}]
Transaction InfoBlock #42071318/Trx 1b9dab4bf94d372c8e3a8ea99663510e5a00c9f4
View Raw JSON Data
{
  "trx_id": "1b9dab4bf94d372c8e3a8ea99663510e5a00c9f4",
  "block": 42071318,
  "trx_in_block": 21,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-29T11:37:48",
  "op": [
    "custom_json",
    {
      "required_auths": [],
      "required_posting_auths": [
        "golibrary"
      ],
      "id": "follow",
      "json": "[\"reblog\",{\"account\":\"golibrary\",\"author\":\"golibrary\",\"permlink\":\"find-all-triplets-with-sum-zero-in-a-given-array\"}]"
    }
  ]
}
golibrarycustom json: follow
2020/03/29 11:37:42
required auths[]
required posting auths["golibrary"]
idfollow
json["reblog",{"account":"golibrary","author":"golibrary","permlink":"depth-of-an-nary-tree-and-finding-route-to-a-node-in-it"}]
Transaction InfoBlock #42071316/Trx f2728c7332087c8d4e312679aa0a5eed368244bf
View Raw JSON Data
{
  "trx_id": "f2728c7332087c8d4e312679aa0a5eed368244bf",
  "block": 42071316,
  "trx_in_block": 9,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-29T11:37:42",
  "op": [
    "custom_json",
    {
      "required_auths": [],
      "required_posting_auths": [
        "golibrary"
      ],
      "id": "follow",
      "json": "[\"reblog\",{\"account\":\"golibrary\",\"author\":\"golibrary\",\"permlink\":\"depth-of-an-nary-tree-and-finding-route-to-a-node-in-it\"}]"
    }
  ]
}
2020/03/28 13:27:57
parent author
parent permlinknary
authorgolibrary
permlinkdepth-of-an-nary-tree-and-finding-route-to-a-node-in-it
titleDepth of an Nary tree and finding route to a node in it
body![N-Ary.jpg](https://cdn.steemitimages.com/DQmVhnE2KDpBcQiMAZ4UNJNx6Ce8c2XN8SWxNRZdeLwZ5me/N-Ary.jpg) DEPTH OF AN N-ARY TREE AND FINDING ROUTE TO A NODE IN AN N-ARY TREE This article is originally published in Golibrary Co Depth of an N-Ary tree and Finding Route to a node in an N-Ary tree Problem Statement:- Given an N-Ary tree, how to find it’s depth and trace route to a destination from a source node of the tree. Consider the below N-Ary tree. In this example, we have used JSON object which contains all the hierarchical representations of an N-Ary tree and thus the traversing algorithm and route tracing algorithms are according to the JSON structure. Click here to see the demo The JSON that represents this tree is: [{ head: '1', id: 'aa', contents: 'Node1', children: [ { head: '2', id: 'a1', contents: 'Node1-Child', children: [ { head: '2.3', id: 'a11', contents: 'Node1.1-Child', children:[{ head: '2.4', id: 'a12', contents: 'Node1.2-Child' }, { head: '2.5', id: 'a13', contents: 'Node1.3-Child' }] } ] }, { head: '3', id: 'a3', contents: 'Node1-Child', children: [ { head: '3.3', id: 'a121', contents: 'Node3.1-Child', children:[{ head: '3.4', id: 'a122', contents: 'Node3.2-Child' }, { head: '3.5', id: 'a133', contents: 'Node3.3-Child' }] } ] }, { head: '4', id: 'a2', contents: 'Node1.2-Child', children: [ { head: '5', id: 'a21', contents: 'Node1.2.1-Child', children:[{head: '5.1', id: 'a245', contents: 'Node1.2.1.1-Child'}]}, { head: '6', id: 'a22', contents: 'Node1.2.2-Child', children:[{head: '6.1', id: 'a2454', contents: 'Node1.2.1.2-Child', children:[{head: '6.2', id: 'a24445', contents: 'Node1.2.1.4-Child', children:[{ head: '6.3', id: 'a1341', contents: 'Node6.2-Child'}]}, ]}]} ] } ] }]; Algorithm for finding depth of tree: 1. Loop through the JSON array and check each Key:Value pair for data type array/object. 2. Recursively invoke the JSON traversing till the last item of JSON array is reached for each such child array obtained in Step 1. Each child array here represents a level of N-Ary tree. Store the levels here for each such child array which represents children of a parent node at a level N. 3.For each JSON object, iterate through the JSON key attributes and recursively invoke JSON traversing for each property in JSON child object be it of type array or object. 4.Once there are no more arrays in Step 2 and no objects/arrays within the parent JSON object, increment the height obtained from step 2 by 1 for accommodating the root of the tree and return it and exit. Below is the JS code for this algorithm: function calcHeight(theObject, height) { if (theObject instanceof Array) { for (var i = 0; i &lt; theObject.length; i++) { //console.log("Node = ", theObject[i].head, "Node Level = ", height); heightOfTree = height; calcHeight(theObject[i], height); } } else { for (var prop in theObject) { if (theObject[prop] instanceof Object || theObject[prop] instanceof Array) { calcHeight(theObject[prop], ++height); } } } return heightOfTree + 1; } Algorithm for tracing route to destination from source node: 1. This reuses the previous algorithm logic to a large extent. Using previous algorithm, obtain a map of Node and the level at which the Node is based. 2. Use the NodeMap from step 1 to find the destination node in the map and save its level. 3. Iterate backwards, through NodeMap again from the index where destination is found. Keep decrementing by one and collect all nodes where the levels are in descending order. 4. Repeat step 3 until root node and slice the collection until destination node by looking up source node in the path obtained as a result of step 3 and 4. Return the sliced collection which will have the path from source to destination in case, if they are directly connected. 5. If there is no direct connectivity between source and destination , then trace route from source till the root and from root till destination and concatenate the results. If there are repeating nodes in this path, get rid of duplicate such nodes and return the final result. If that’s not the case, return concatenated results as is. Also Read: https://www.golibrary.co/finding-diameter-of-a-binary-tree/ Below is the Algorithm for extracting shortest path from a given path: function findShortestPath(path) { var index1, index2, arr1, arr2; for (i = path.length - 1; i &gt;= 0; i--) { for (j = i - 1; j &gt;= 0; j--) { if (path[i] === path[j]) { index1 = i; index2 = j; arr1 = path.slice().slice(0, index2); arr2 = path.slice().slice(index1, path.length); return arr1.concat(arr2); } } } return null; } JS code for the above algorithm is as below: function getRoute() { var source = document.getElementById("source").value, destination = document.getElementById("destination").value; var path = traceRoute(source, destination); if (path instanceof Array) { document.getElementById("route").innerHTML = " <h2>Route from Nodes : " + source + " to " + destination + " is : " + path.join("-&gt;") + "</h2> "; } else if (path === -1) { document.getElementById("route").innerHTML = " <h2>Invalid Input : Either of the Nodes, " + source + " or " + destination + " you entered doesn't exist in the tree!!</h2> "; } else { document.getElementById("route").innerHTML = " <h2>Node " + destination + " isn't reachable from Node " + source + "</h2> "; } } function traceRoute(source, destination) { var routes = findRoute(jsonObject, 0), pivot = -1, spivot = -1; for (var index = 0; index &lt; routes.length; index++) { if (destination === routes[index].node) { pivot = index; } if (source === routes[index].node) { spivot = index; } } if (pivot === -1 || spivot === -1) { return -1; } var path = routes[pivot].node; var level = routes[pivot].level; while (pivot &gt; 0) { pivot--; if (level - routes[pivot].level === 1) { path += "|" + routes[pivot].node; level = routes[pivot].level; } } var routeArr = path.split("|").reverse(); if (routeArr.some(function(item, index) { if (item === source) { routeArr = routeArr.splice(routeArr.indexOf(source), routeArr.length); return true; } })) { return routeArr; } else { // try finding shortest path first if it exists //var finalRoute = findShortestPath(source, destination); // else try again here as nodes could be reachable via root and shortest path is not found var route1 = traceRoute(routeMap[0].node, source).reverse(); var arr = traceRoute(routeMap[0].node, destination); var route2 = (routeMap[0].node === destination) ? [] : arr.slice(1, arr.length); var finalPath = route1.concat(route2); var shortestPath = findShortestPath(finalPath); if (shortestPath) { return shortestPath; } else { return route1.concat(route2); } } } function findRoute(theObject, height) { if (theObject instanceof Array) { for (var i = 0; i &lt; theObject.length; i++) { console.log("Node = ", theObject[i].head, "Node Level = ", height); var object = { "node": theObject[i].head, "level": height }; routeMap.push(object); findRoute(theObject[i], height); } } else { for (var prop in theObject) { if (theObject[prop] instanceof Object || theObject[prop] instanceof Array) { findRoute(theObject[prop], ++height); } } } return routeMap; } This article was originally published on :- https://www.golibrary.co/depth-route-node-n-ary-tree/ Hope you enjoyed reading this. Like us on https://www.facebook.com/golibraryco & https://linkedin.com/company/golibrary for more interesting reads like this.
json metadata{"tags":["nary","tree","datastructures","algorithms","javascript"],"image":["https://cdn.steemitimages.com/DQmVhnE2KDpBcQiMAZ4UNJNx6Ce8c2XN8SWxNRZdeLwZ5me/N-Ary.jpg"],"links":["https://www.golibrary.co/finding-diameter-of-a-binary-tree/","https://www.golibrary.co/depth-route-node-n-ary-tree/","https://www.facebook.com/golibraryco","https://linkedin.com/company/golibrary"],"app":"steemit/0.2","format":"markdown"}
Transaction InfoBlock #42045118/Trx da3382b96f1088e896b1ec688c9c924da7ec5a62
View Raw JSON Data
{
  "trx_id": "da3382b96f1088e896b1ec688c9c924da7ec5a62",
  "block": 42045118,
  "trx_in_block": 13,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-28T13:27:57",
  "op": [
    "comment",
    {
      "parent_author": "",
      "parent_permlink": "nary",
      "author": "golibrary",
      "permlink": "depth-of-an-nary-tree-and-finding-route-to-a-node-in-it",
      "title": "Depth of an Nary tree and finding route to a node in it",
      "body": "![N-Ary.jpg](https://cdn.steemitimages.com/DQmVhnE2KDpBcQiMAZ4UNJNx6Ce8c2XN8SWxNRZdeLwZ5me/N-Ary.jpg)\n\n\n\nDEPTH OF AN N-ARY TREE AND FINDING ROUTE TO A NODE IN AN N-ARY TREE\n\n\n\nThis article is originally published in Golibrary Co\n\n\nDepth of an N-Ary tree and Finding Route to a node in an N-Ary tree\n \nProblem Statement:- Given an N-Ary tree, how to find it’s depth and trace route to a destination from a source node of the tree.\n \nConsider the below N-Ary tree. In this example, we have used JSON object which contains all the hierarchical representations of an N-Ary tree and thus the traversing algorithm and route tracing algorithms are according to the JSON structure.\n \nClick here to see the demo\n\n\nThe JSON that represents this tree is:\n\n[{\nhead: '1',\nid: 'aa',\ncontents: 'Node1',\nchildren: [\n{\nhead: '2',\nid: 'a1',\ncontents: 'Node1-Child',\nchildren: [\n{ head: '2.3', id: 'a11', contents: 'Node1.1-Child', children:[{ head: '2.4', id: 'a12', contents: 'Node1.2-Child' },\n{ head: '2.5', id: 'a13', contents: 'Node1.3-Child' }] }\n\n]\n},\n{\nhead: '3',\nid: 'a3',\ncontents: 'Node1-Child',\nchildren: [\n{ head: '3.3', id: 'a121', contents: 'Node3.1-Child', children:[{ head: '3.4', id: 'a122', contents: 'Node3.2-Child' },\n{ head: '3.5', id: 'a133', contents: 'Node3.3-Child' }] }\n]\n},\n{\nhead: '4',\nid: 'a2',\ncontents: 'Node1.2-Child',\nchildren: [\n{ head: '5', id: 'a21', contents: 'Node1.2.1-Child', children:[{head: '5.1', id: 'a245', contents: 'Node1.2.1.1-Child'}]},\n{ head: '6', id: 'a22', contents: 'Node1.2.2-Child', children:[{head: '6.1', id: 'a2454', contents: 'Node1.2.1.2-Child',\nchildren:[{head: '6.2', id: 'a24445', contents: 'Node1.2.1.4-Child',\nchildren:[{ head: '6.3', id: 'a1341', contents: 'Node6.2-Child'}]},\n]}]}\n]\n}\n]\n}];\n\nAlgorithm for finding depth of tree:\n1. Loop through the JSON array and check each Key:Value pair for data type array/object.\n \n2. Recursively invoke the JSON traversing till the last item of JSON array is reached for each such child array obtained in Step 1. Each child array here represents a level of N-Ary tree. Store the levels here for each such child array which represents children of a parent node at a level N.\n \n3.For each JSON object, iterate through the JSON key attributes and recursively invoke JSON traversing for each property in JSON child object be it of type array or object.\n \n4.Once there are no more arrays in Step 2 and no objects/arrays within the parent JSON object, increment the height obtained from step 2 by 1 for accommodating the root of the tree and return it and exit.\n \nBelow is the JS code for this algorithm:\n \nfunction calcHeight(theObject, height) {\nif (theObject instanceof Array) {\nfor (var i = 0; i &lt; theObject.length; i++) {\n//console.log(\"Node = \", theObject[i].head, \"Node Level = \", height);\nheightOfTree = height;\ncalcHeight(theObject[i], height);\n}\n} else {\nfor (var prop in theObject) {\nif (theObject[prop] instanceof Object || theObject[prop] instanceof Array) {\ncalcHeight(theObject[prop], ++height);\n}\n}\n}\nreturn heightOfTree + 1;\n}\n Algorithm for tracing route to destination from source node:\n1. This reuses the previous algorithm logic to a large extent. Using previous algorithm, obtain a map of Node and the level at which the Node is based.\n \n2. Use the NodeMap from step 1 to find the destination node in the map and save its level.\n \n3. Iterate backwards, through NodeMap again from the index where destination is found. Keep decrementing by one and collect all nodes where the levels are in descending order.\n \n4. Repeat step 3 until root node and slice the collection until destination node by looking up source node in the path obtained as a result of step 3 and 4. Return the sliced collection which will have the path from source to destination in case, if they are directly connected.\n \n5. If there is no direct connectivity between source and destination , then trace route from source till the root and from root till destination and concatenate the results. If there are repeating nodes in this path, get rid of duplicate such nodes and return the final result. If that’s not the case, return concatenated results as is.\n \nAlso Read: https://www.golibrary.co/finding-diameter-of-a-binary-tree/\n \n \nBelow is the Algorithm for extracting shortest path from a given path:\nfunction findShortestPath(path) {\nvar index1, index2, arr1, arr2;\nfor (i = path.length - 1; i &gt;= 0; i--) {\nfor (j = i - 1; j &gt;= 0; j--) {\nif (path[i] === path[j]) {\nindex1 = i;\nindex2 = j;\narr1 = path.slice().slice(0, index2);\narr2 = path.slice().slice(index1, path.length);\nreturn arr1.concat(arr2);\n}\n}\n}\nreturn null;\n}\n \n \nJS code for the above algorithm is as below:\nfunction getRoute() {\nvar source = document.getElementById(\"source\").value,\ndestination = document.getElementById(\"destination\").value;\nvar path = traceRoute(source, destination);\n \nif (path instanceof Array) {\ndocument.getElementById(\"route\").innerHTML = \"\n<h2>Route from Nodes : \" + source + \" to \" + destination + \" is :\n\" + path.join(\"-&gt;\") + \"</h2>\n\";\n} else if (path === -1) {\ndocument.getElementById(\"route\").innerHTML = \"\n<h2>Invalid Input : Either of the Nodes, \" + source + \" or \" + destination +\n\" you entered doesn't exist in the tree!!</h2>\n\";\n} else {\ndocument.getElementById(\"route\").innerHTML = \"\n<h2>Node \" + destination + \" isn't reachable from Node \" + source + \"</h2>\n\";\n}\n}\n \nfunction traceRoute(source, destination) {\nvar routes = findRoute(jsonObject, 0),\npivot = -1,\nspivot = -1;\nfor (var index = 0; index &lt; routes.length; index++) { if (destination === routes[index].node) { pivot = index; } if (source === routes[index].node) { spivot = index; } } if (pivot === -1 || spivot === -1) { return -1; } var path = routes[pivot].node; var level = routes[pivot].level; while (pivot &gt; 0) {\npivot--;\nif (level - routes[pivot].level === 1) {\npath += \"|\" + routes[pivot].node;\nlevel = routes[pivot].level;\n}\n}\n \nvar routeArr = path.split(\"|\").reverse();\nif (routeArr.some(function(item, index) {\nif (item === source) {\nrouteArr = routeArr.splice(routeArr.indexOf(source), routeArr.length);\nreturn true;\n}\n})) {\nreturn routeArr;\n} else {\n// try finding shortest path first if it exists\n//var finalRoute = findShortestPath(source, destination);\n// else try again here as nodes could be reachable via root and shortest path is not found\nvar route1 = traceRoute(routeMap[0].node, source).reverse();\nvar arr = traceRoute(routeMap[0].node, destination);\nvar route2 = (routeMap[0].node === destination) ? [] : arr.slice(1, arr.length);\nvar finalPath = route1.concat(route2);\nvar shortestPath = findShortestPath(finalPath);\nif (shortestPath) {\nreturn shortestPath;\n} else {\nreturn route1.concat(route2);\n}\n}\n}\n \nfunction findRoute(theObject, height) {\nif (theObject instanceof Array) {\nfor (var i = 0; i &lt; theObject.length; i++) {\nconsole.log(\"Node = \", theObject[i].head, \"Node Level = \", height);\nvar object = {\n\"node\": theObject[i].head,\n\"level\": height\n};\n \nrouteMap.push(object);\nfindRoute(theObject[i], height);\n}\n} else {\nfor (var prop in theObject) {\nif (theObject[prop] instanceof Object || theObject[prop] instanceof Array) {\nfindRoute(theObject[prop], ++height);\n}\n}\n}\nreturn routeMap;\n}\n\n\nThis article was originally published on :- https://www.golibrary.co/depth-route-node-n-ary-tree/\n\nHope you enjoyed reading this. Like us on https://www.facebook.com/golibraryco &\n\nhttps://linkedin.com/company/golibrary for more  interesting reads like this.",
      "json_metadata": "{\"tags\":[\"nary\",\"tree\",\"datastructures\",\"algorithms\",\"javascript\"],\"image\":[\"https://cdn.steemitimages.com/DQmVhnE2KDpBcQiMAZ4UNJNx6Ce8c2XN8SWxNRZdeLwZ5me/N-Ary.jpg\"],\"links\":[\"https://www.golibrary.co/finding-diameter-of-a-binary-tree/\",\"https://www.golibrary.co/depth-route-node-n-ary-tree/\",\"https://www.facebook.com/golibraryco\",\"https://linkedin.com/company/golibrary\"],\"app\":\"steemit/0.2\",\"format\":\"markdown\"}"
    }
  ]
}
2020/03/28 13:18:42
parent author
parent permlinkalgorithms
authorgolibrary
permlinkfind-all-triplets-with-sum-zero-in-a-given-array
titleFind all triplets with sum zero in a given array
body![triplet_sum.png](https://cdn.steemitimages.com/DQmZpfpW7r41TM9HWefw1PC8UijcNdS5mAo3qDKuNniQWsZ/triplet_sum.png) Problem Statement Given an array of unsorted numbers, find all unique triplets in it that add up to zero. Example 1: Input: [-3, 0, 1, 2, –1, 1, –2] Output: [-3, 1, 2], [-2, 0, 2], [-2, 1, 1], [-1, 0, 1] Explanation: There are four unique triplets whose sum is equal to zero. Example 2: Input: [-5, 2, –1, –2, 3] Output: [[-5, 2, 3], [-2, –1, 3]] Explanation: There are two unique triplets whose sum is equal to zero. Solution This problem follows the Two Pointers pattern and shares similarities with Pair with Target Sum. A couple of differences are that the input array is not sorted and instead of a pair we need to find triplets with a target sum of zero. To follow a similar approach, first, we will sort the array and then iterate through it taking one number at a time. Let’s say during our iteration we are at number ‘X’, so we need to find ‘Y’ and ‘Z’ such that X + Y + Z =0. At this stage, our problem translates into finding a pair whose sum is equal to “−X” (as from the above equation Y + Z == -X). Another difference from Pair with Target Sum is that we need to find all the unique triplets. To handle this, we have to skip any duplicate number. Since we will be sorting the array, so all the duplicate numbers will be next to each other and are easier to skip. Below is the code written in Javascript: /** * @param {number[]} nums * @return {number[][]} */ function tripletSum(nums) { nums.sort((a,b)=>a-b); let triplets = []; for (var i = 0; i < nums.length; i++) { if (i > 0 && nums[i] === nums[i-1]) { // skip duplicate elements continue; } // for each nums[i] or element, search pair such that their sum equals -nums[i] search_pair(nums, -nums[i], i+1, triplets) } return triplets; }; function search_pair(arr, target_sum, index, triplets) { let low = index, high = arr.length - 1; while (low < high) { if (arr[low] + arr[high] === target_sum) { triplets.push([-target_sum, arr[low], arr[high]]); low++; high--; while (low < high && arr[low] === arr[low-1]) low++; while (low < high && arr[high] === arr[high+1]) high--; } else if (target_sum > arr[low] + arr[high]) { low++; } else { high--; } } } document.write(tripletSum([-3, 0, 1, 2, -1, 1, -2])+'<br/>'); document.write(tripletSum([-5, 2, -1, -2, 3])+'<br/>'); document.write(tripletSum([-1, 0, 1, 2, -1, -4])+'<br/>'); Time complexity Sorting the array will take O(N * logN). The search_pair() function will take O(N). As we are calling search_pair() for every number in the input array, this means that overall tripletSum() will take O(N * logN + N^2), which is asymptotically equivalent to O(N^2). Space complexity Ignoring the space required for the output array, the space complexity of the above algorithm will be O(N) which is required for sorting. This article was originally published on Golibrary (https://www.golibrary.co/find-all-triplets-with-sum-zero-in-an-array/)
json metadata{"tags":["algorithms","javascript","arrays","triplet","zero","sum"],"users":["param","return"],"image":["https://cdn.steemitimages.com/DQmZpfpW7r41TM9HWefw1PC8UijcNdS5mAo3qDKuNniQWsZ/triplet_sum.png"],"links":["https://www.golibrary.co/find-all-triplets-with-sum-zero-in-an-array/"],"app":"steemit/0.2","format":"markdown"}
Transaction InfoBlock #42044934/Trx 89726f39db43dea4f4b78b44b378e43c8dd2e9f2
View Raw JSON Data
{
  "trx_id": "89726f39db43dea4f4b78b44b378e43c8dd2e9f2",
  "block": 42044934,
  "trx_in_block": 7,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-28T13:18:42",
  "op": [
    "comment",
    {
      "parent_author": "",
      "parent_permlink": "algorithms",
      "author": "golibrary",
      "permlink": "find-all-triplets-with-sum-zero-in-a-given-array",
      "title": "Find all triplets with sum zero in a given array",
      "body": "![triplet_sum.png](https://cdn.steemitimages.com/DQmZpfpW7r41TM9HWefw1PC8UijcNdS5mAo3qDKuNniQWsZ/triplet_sum.png)\n\n\nProblem Statement\n \nGiven an array of unsorted numbers, find all unique triplets in it that add up to zero.\n \nExample 1:\n \nInput: [-3, 0, 1, 2, –1, 1, –2]\nOutput: [-3, 1, 2], [-2, 0, 2], [-2, 1, 1], [-1, 0, 1]\nExplanation: There are four unique triplets whose sum is equal to zero.\n \nExample 2:\n \nInput: [-5, 2, –1, –2, 3]\nOutput: [[-5, 2, 3], [-2, –1, 3]]\nExplanation: There are two unique triplets whose sum is equal to zero.\n \n \n \nSolution\n \nThis problem follows the Two Pointers pattern and shares similarities with Pair with Target Sum. A couple of differences are that the input array is not sorted and instead of a pair we need to find triplets with a target sum of zero.\nTo follow a similar approach, first, we will sort the array and then iterate through it taking one number at a time. Let’s say during our iteration we are at number ‘X’, so we need to find ‘Y’ and ‘Z’ such that X + Y + Z =0. At this stage, our problem translates into finding a pair whose sum is equal to “−X” (as from the above equation Y + Z == -X).\nAnother difference from Pair with Target Sum is that we need to find all the unique triplets. To handle this, we have to skip any duplicate number. Since we will be sorting the array, so all the duplicate numbers will be next to each other and are easier to skip.\n \nBelow is the code written in Javascript:\n\n\n\n/**\n * @param {number[]} nums\n * @return {number[][]}\n */\nfunction tripletSum(nums) {\n    nums.sort((a,b)=>a-b);\n    let triplets = [];\n    \n    for (var i = 0; i < nums.length; i++) {\n        if (i > 0 && nums[i] === nums[i-1]) {   // skip duplicate elements\n            continue;\n        }\n        // for each nums[i] or element, search pair such that their sum equals -nums[i]\n        search_pair(nums, -nums[i], i+1, triplets)\n    }\n    return triplets;\n};\n\n\n\nfunction search_pair(arr, target_sum, index, triplets) {\n    let low = index, high = arr.length - 1;\n    \n    while (low < high) {\n        if (arr[low] + arr[high] === target_sum) {\n            triplets.push([-target_sum, arr[low], arr[high]]);\n            low++;\n            high--;\n        \n            while (low < high && arr[low] === arr[low-1]) low++;\n        \n            while (low < high && arr[high] === arr[high+1]) high--;     \n            \n        } else if (target_sum > arr[low] + arr[high]) {\n            low++;\n        } else {\n            high--;\n        }    \n    } \n}\n\n\ndocument.write(tripletSum([-3, 0, 1, 2, -1, 1, -2])+'<br/>');\ndocument.write(tripletSum([-5, 2, -1, -2, 3])+'<br/>');\ndocument.write(tripletSum([-1, 0, 1, 2, -1, -4])+'<br/>');\n\n\n\n\n\n\n\n\nTime complexity\n \nSorting the array will take O(N * logN). The search_pair() function will take O(N).\nAs we are calling search_pair() for every number in the input array, this means that overall tripletSum() will take O(N * logN + N^2), which is asymptotically equivalent to O(N^2).\n \nSpace complexity\n \nIgnoring the space required for the output array, the space complexity of the above algorithm will be O(N) which is required for sorting.\n \n \n\n\n\n\n\nThis article was originally published on Golibrary (https://www.golibrary.co/find-all-triplets-with-sum-zero-in-an-array/)",
      "json_metadata": "{\"tags\":[\"algorithms\",\"javascript\",\"arrays\",\"triplet\",\"zero\",\"sum\"],\"users\":[\"param\",\"return\"],\"image\":[\"https://cdn.steemitimages.com/DQmZpfpW7r41TM9HWefw1PC8UijcNdS5mAo3qDKuNniQWsZ/triplet_sum.png\"],\"links\":[\"https://www.golibrary.co/find-all-triplets-with-sum-zero-in-an-array/\"],\"app\":\"steemit/0.2\",\"format\":\"markdown\"}"
    }
  ]
}
golibraryreceived 0.059 STEEM, 0.073 SP author reward for @golibrary / findlongestsubstringwithnorepeatingcharacters-j0xygxngn7
2020/03/28 04:12:00
authorgolibrary
permlinkfindlongestsubstringwithnorepeatingcharacters-j0xygxngn7
sbd payout0.000 SBD
steem payout0.059 STEEM
vesting payout119.422813 VESTS
Transaction InfoBlock #42034164/Virtual Operation #5
View Raw JSON Data
{
  "trx_id": "0000000000000000000000000000000000000000",
  "block": 42034164,
  "trx_in_block": 4294967295,
  "op_in_trx": 0,
  "virtual_op": 5,
  "timestamp": "2020-03-28T04:12:00",
  "op": [
    "author_reward",
    {
      "author": "golibrary",
      "permlink": "findlongestsubstringwithnorepeatingcharacters-j0xygxngn7",
      "sbd_payout": "0.000 SBD",
      "steem_payout": "0.059 STEEM",
      "vesting_payout": "119.422813 VESTS"
    }
  ]
}
steempressreceived 0.013 SP benefactor reward from @golibrary
2020/03/28 04:12:00
benefactorsteempress
authorgolibrary
permlinkfindlongestsubstringwithnorepeatingcharacters-j0xygxngn7
sbd payout0.000 SBD
steem payout0.010 STEEM
vesting payout21.535261 VESTS
Transaction InfoBlock #42034164/Virtual Operation #4
View Raw JSON Data
{
  "trx_id": "0000000000000000000000000000000000000000",
  "block": 42034164,
  "trx_in_block": 4294967295,
  "op_in_trx": 0,
  "virtual_op": 4,
  "timestamp": "2020-03-28T04:12:00",
  "op": [
    "comment_benefactor_reward",
    {
      "benefactor": "steempress",
      "author": "golibrary",
      "permlink": "findlongestsubstringwithnorepeatingcharacters-j0xygxngn7",
      "sbd_payout": "0.000 SBD",
      "steem_payout": "0.010 STEEM",
      "vesting_payout": "21.535261 VESTS"
    }
  ]
}
2020/03/27 11:56:57
voterpayroll
authorgolibrary
permlinksquaring-a-sorted-array
weight200 (2.00%)
Transaction InfoBlock #42014920/Trx 2b3a6bc794f7126b38d1d6511beb58cc7dd5e925
View Raw JSON Data
{
  "trx_id": "2b3a6bc794f7126b38d1d6511beb58cc7dd5e925",
  "block": 42014920,
  "trx_in_block": 20,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-27T11:56:57",
  "op": [
    "vote",
    {
      "voter": "payroll",
      "author": "golibrary",
      "permlink": "squaring-a-sorted-array",
      "weight": 200
    }
  ]
}
golibrarypublished a new post: squaring-a-sorted-array
2020/03/27 11:37:54
parent author
parent permlinksquared
authorgolibrary
permlinksquaring-a-sorted-array
titleSQUARING A SORTED ARRAY
body![squared-sorted-array-770x300.png](https://cdn.steemitimages.com/DQmby7oVbjW9F8EoXF41LJydavgeBEkoHB2m91DPNVvjD55/squared-sorted-array-770x300.png) Problem Statement Given a sorted array, create a new array containing squares of all the number of the input array in the sorted order. Example 1: Input: [-2, –1, 0, 2, 3] Output: [0, 1, 4, 4, 9] Example 2: Input: [-3, –1, 0, 1, 2] Output: [0 1 1 4 9] Solution 1 One simple solution is to loop through the array elements and square them in place and then store the sorted squared array in output squares array and return it. Javascript code below:- 1 2 function make_squares(arr) { 3 squares = [] 4 // TODO: Write your code here 5 arr = arr.map(item=>item*item); 6 squares = arr.sort((a,b)=>a-b); 7 return squares; 8 }; 9 ​ 10 document.write(`Squares: ${make_squares([-2, -1, 0, 2, 3])}<br/>`); 11 document.write(`Squares: ${make_squares([-3, -1, 0, 1, 2])}<br/>`); 12 13 ​ Time complexity The time complexity of the above algorithm will be O(N log N) as we are first sorting the array and then iterating the input array only once. Space complexity The space complexity of the above algorithm will also be O(N); this space will be used for the output array. The above solution works but isn’t efficient as we are sorting and then iterating through the array again to store it in squares array. Better solution would be to use a 2 pointer approach and binary search mechanism to insert the squared elements in a sorted way as we iterate through the array. Solution 2 This question becomes tricky because the array has negative numbers as well. An easier approach could be to first find the index of the first non-negative number in the array. After that, we can use Two Pointers to iterate the array. One pointer will move forward to iterate the non-negative numbers and the other pointer will move backward to iterate the negative numbers. At any step, whichever number gives us a bigger square will be added to the output array. For the above-mentioned Example-1, we will do something like this: Squared Sorted Array Squared Sorted Array1 Since the numbers at both the ends can give us the largest square, an alternate approach could be to use two pointers starting at both the ends of the input array to iterate faster. At any step, whichever pointer gives us the bigger square we add it to the result array and move to the next/previous number according to the pointer. For the above-mentioned Example-1, we will do something like this: Squared sorted array 2 Squared sorted array 2 Javascript code below:- 1 2 function make_squares(arr) { 3 const n = arr.length; 4 squares = Array(n).fill(0); 5 let highestSquareIdx = n - 1; 6 let left = 0, 7 right = n - 1; 8 while (left <= right) { 9 let leftSquare = arr[left] * arr[left], 10 rightSquare = arr[right] * arr[right]; 11 if (leftSquare > rightSquare) { 12 squares[highestSquareIdx] = leftSquare; 13 left += 1; 14 } else { 15 squares[highestSquareIdx] = rightSquare; 16 right -= 1; 17 } 18 highestSquareIdx -= 1; 19 } 20 ​ 21 return squares; 22 } 23 ​ 24 ​ 25 document.write(`Squares: ${make_squares([-2, -1, 0, 2, 3])}<br/>`); 26 document.write(`Squares: ${make_squares([-3, -1, 0, 1, 2])}<br/>`); 27 Time complexity The time complexity of the above algorithm will be O(N) as we sorting and squaring the array in the same iteration. Space complexity The space complexity of the above algorithm will also be O(N); this space will be used for the output array. Posted from my blog with SteemPress : https://www.golibrary.
json metadata{"tags":["squared","sorted","arrays","algorithms","golibrary"],"image":["https://cdn.steemitimages.com/DQmby7oVbjW9F8EoXF41LJydavgeBEkoHB2m91DPNVvjD55/squared-sorted-array-770x300.png"],"links":["https://www.golibrary"],"app":"steemit/0.2","format":"markdown"}
Transaction InfoBlock #42014545/Trx c6f17a3d664c03dffaa38ea3800e9bc6b77fbe85
View Raw JSON Data
{
  "trx_id": "c6f17a3d664c03dffaa38ea3800e9bc6b77fbe85",
  "block": 42014545,
  "trx_in_block": 6,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-27T11:37:54",
  "op": [
    "comment",
    {
      "parent_author": "",
      "parent_permlink": "squared",
      "author": "golibrary",
      "permlink": "squaring-a-sorted-array",
      "title": "SQUARING A SORTED ARRAY",
      "body": "![squared-sorted-array-770x300.png](https://cdn.steemitimages.com/DQmby7oVbjW9F8EoXF41LJydavgeBEkoHB2m91DPNVvjD55/squared-sorted-array-770x300.png)\n\n\n\nProblem Statement\n \n\nGiven a sorted array, create a new array containing squares of all the number of the input array in the sorted order.\n\n \n\nExample 1:\n\n \n\nInput: [-2, –1, 0, 2, 3]\n\nOutput: [0, 1, 4, 4, 9]\n \n\nExample 2:\n\n \n\n \n\nInput: [-3, –1, 0, 1, 2]\n \n\nOutput: [0 1 1 4 9]\n\nSolution 1\n\nOne simple solution is to loop through the array elements and square them in place and then store the sorted squared array in output squares array and return it.\n\nJavascript code below:-\n\n \n \n\n1\n\n2\nfunction make_squares(arr) {\n3\n  squares = []\n4\n  // TODO: Write your code here\n5\n  arr = arr.map(item=>item*item);\n6\n  squares = arr.sort((a,b)=>a-b);\n7\n  return squares;\n8\n};\n9\n​\n10\ndocument.write(`Squares: ${make_squares([-2, -1, 0, 2, 3])}<br/>`);\n11\ndocument.write(`Squares: ${make_squares([-3, -1, 0, 1, 2])}<br/>`);\n12\n\n13\n​\n \n \n\nTime complexity\n \n\nThe time complexity of the above algorithm will be O(N log N) as we are first sorting the array and then iterating the input array only once.\n\n \n \n\nSpace complexity\n \n\nThe space complexity of the above algorithm will also be O(N); this space will be used for the output array.\n\nThe above solution works but isn’t efficient as we are sorting and then iterating through the array again to store it in squares array. Better solution would be to use a 2 pointer approach and binary search mechanism to insert the squared elements in a sorted way as we iterate through the array. \n\n \n \n\nSolution 2\n\n \n\nThis question becomes tricky because the array has negative numbers as well. An easier approach could be to first find the index of the first non-negative number in the array. After that, we can use Two Pointers to iterate the array. One pointer will move forward to iterate the non-negative numbers and the other pointer will move backward to iterate the negative numbers. At any step, whichever number gives us a bigger square will be added to the output array.\n\n \n\nFor the above-mentioned Example-1, we will do something like this:\n\n \n\nSquared Sorted Array\nSquared Sorted Array1\n\n \n\n \n\nSince the numbers at both the ends can give us the largest square, an alternate approach could be to use two pointers starting at both the ends of the input array to iterate faster. At any step, whichever pointer gives us the bigger square we add it to the result array and move to the next/previous number according to the pointer. For the above-mentioned Example-1, we will do something like this:\n\n \n\n \n\nSquared sorted array 2\nSquared sorted array 2\n\n \n\n \n\n \n\nJavascript code below:-\n\n \n\n \n\n1\n\n2\nfunction make_squares(arr) {\n3\n  const n = arr.length;\n4\n  squares = Array(n).fill(0);\n5\n  let highestSquareIdx = n - 1;\n6\n  let left = 0,\n7\n    right = n - 1;\n8\n  while (left <= right) {\n9\n    let leftSquare = arr[left] * arr[left],\n10\n      rightSquare = arr[right] * arr[right];\n11\n    if (leftSquare > rightSquare) {\n12\n      squares[highestSquareIdx] = leftSquare;\n13\n      left += 1;\n14\n    } else {\n15\n      squares[highestSquareIdx] = rightSquare;\n16\n      right -= 1;\n17\n    }\n18\n    highestSquareIdx -= 1;\n19\n  }\n20\n​\n21\n  return squares;\n22\n}\n23\n​\n24\n​\n25\ndocument.write(`Squares: ${make_squares([-2, -1, 0, 2, 3])}<br/>`);\n26\ndocument.write(`Squares: ${make_squares([-3, -1, 0, 1, 2])}<br/>`);\n27\n\n \n\n \n\n \n\nTime complexity\n \n\nThe time complexity of the above algorithm will be O(N) as we sorting and squaring the array in the same iteration.\n\n \n \n\nSpace complexity\n \n\nThe space complexity of the above algorithm will also be O(N); this space will be used for the output array.\n\n \n\n\n  \nPosted from my blog with SteemPress : https://www.golibrary.",
      "json_metadata": "{\"tags\":[\"squared\",\"sorted\",\"arrays\",\"algorithms\",\"golibrary\"],\"image\":[\"https://cdn.steemitimages.com/DQmby7oVbjW9F8EoXF41LJydavgeBEkoHB2m91DPNVvjD55/squared-sorted-array-770x300.png\"],\"links\":[\"https://www.golibrary\"],\"app\":\"steemit/0.2\",\"format\":\"markdown\"}"
    }
  ]
}
2020/03/25 13:02:57
authorgolibrary
permlinklengthofsmallestsubarraywithasumgreaterthanorequaltos-51dajsyr1f
sbd payout0.000 SBD
steem payout0.063 STEEM
vesting payout123.354460 VESTS
Transaction InfoBlock #41959341/Virtual Operation #6
View Raw JSON Data
{
  "trx_id": "0000000000000000000000000000000000000000",
  "block": 41959341,
  "trx_in_block": 4294967295,
  "op_in_trx": 0,
  "virtual_op": 6,
  "timestamp": "2020-03-25T13:02:57",
  "op": [
    "author_reward",
    {
      "author": "golibrary",
      "permlink": "lengthofsmallestsubarraywithasumgreaterthanorequaltos-51dajsyr1f",
      "sbd_payout": "0.000 SBD",
      "steem_payout": "0.063 STEEM",
      "vesting_payout": "123.354460 VESTS"
    }
  ]
}
steempressreceived 0.013 SP benefactor reward from @golibrary
2020/03/25 13:02:57
benefactorsteempress
authorgolibrary
permlinklengthofsmallestsubarraywithasumgreaterthanorequaltos-51dajsyr1f
sbd payout0.000 SBD
steem payout0.011 STEEM
vesting payout21.538080 VESTS
Transaction InfoBlock #41959341/Virtual Operation #5
View Raw JSON Data
{
  "trx_id": "0000000000000000000000000000000000000000",
  "block": 41959341,
  "trx_in_block": 4294967295,
  "op_in_trx": 0,
  "virtual_op": 5,
  "timestamp": "2020-03-25T13:02:57",
  "op": [
    "comment_benefactor_reward",
    {
      "benefactor": "steempress",
      "author": "golibrary",
      "permlink": "lengthofsmallestsubarraywithasumgreaterthanorequaltos-51dajsyr1f",
      "sbd_payout": "0.000 SBD",
      "steem_payout": "0.011 STEEM",
      "vesting_payout": "21.538080 VESTS"
    }
  ]
}
2020/03/22 17:10:30
parent authorgolibrary
parent permlinkfindlongestsubstringwithnorepeatingcharacters-j0xygxngn7
authorremlaps-lite
permlinkre-golibrary-q7ludi
title
bodyHi, thanks for the post! I included a link to it in my daily [Science and technology digest](/@remlaps-lite/curating-the-internet-science-and-technology-digest-for-march-22-2020), and you'll get a 10% share of that post's rewards.
json metadata{"tags":["steempress"],"app":"steempeak/2020.03.6"}
Transaction InfoBlock #41878986/Trx cd9c7250404c73491a28e81e1c962867118ec68e
View Raw JSON Data
{
  "trx_id": "cd9c7250404c73491a28e81e1c962867118ec68e",
  "block": 41878986,
  "trx_in_block": 35,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-22T17:10:30",
  "op": [
    "comment",
    {
      "parent_author": "golibrary",
      "parent_permlink": "findlongestsubstringwithnorepeatingcharacters-j0xygxngn7",
      "author": "remlaps-lite",
      "permlink": "re-golibrary-q7ludi",
      "title": "",
      "body": "Hi, thanks for the post! I included a link to it in my daily [Science and technology digest](/@remlaps-lite/curating-the-internet-science-and-technology-digest-for-march-22-2020), and you'll get a 10% share of that post's rewards.",
      "json_metadata": "{\"tags\":[\"steempress\"],\"app\":\"steempeak/2020.03.6\"}"
    }
  ]
}
2020/03/21 19:43:30
voterremlaps-lite
authorgolibrary
permlinkfindlongestsubstringwithnorepeatingcharacters-j0xygxngn7
weight10000 (100.00%)
Transaction InfoBlock #41853606/Trx f9371732348fcbe6d96fcd3190d4cd861f78195e
View Raw JSON Data
{
  "trx_id": "f9371732348fcbe6d96fcd3190d4cd861f78195e",
  "block": 41853606,
  "trx_in_block": 17,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-21T19:43:30",
  "op": [
    "vote",
    {
      "voter": "remlaps-lite",
      "author": "golibrary",
      "permlink": "findlongestsubstringwithnorepeatingcharacters-j0xygxngn7",
      "weight": 10000
    }
  ]
}
2020/03/21 11:37:21
voternin4i
authorgolibrary
permlinkfindlongestsubstringwithnorepeatingcharacters-j0xygxngn7
weight10000 (100.00%)
Transaction InfoBlock #41844003/Trx 5b969446cf7ade242b29876a15027ca3d6e5476f
View Raw JSON Data
{
  "trx_id": "5b969446cf7ade242b29876a15027ca3d6e5476f",
  "block": 41844003,
  "trx_in_block": 22,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-21T11:37:21",
  "op": [
    "vote",
    {
      "voter": "nin4i",
      "author": "golibrary",
      "permlink": "findlongestsubstringwithnorepeatingcharacters-j0xygxngn7",
      "weight": 10000
    }
  ]
}
2020/03/21 04:42:03
voterpayroll
authorgolibrary
permlinkfindlongestsubstringwithnorepeatingcharacters-j0xygxngn7
weight100 (1.00%)
Transaction InfoBlock #41835817/Trx 51fee5dee26f5146f8ba22817560831086e28270
View Raw JSON Data
{
  "trx_id": "51fee5dee26f5146f8ba22817560831086e28270",
  "block": 41835817,
  "trx_in_block": 4,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-21T04:42:03",
  "op": [
    "vote",
    {
      "voter": "payroll",
      "author": "golibrary",
      "permlink": "findlongestsubstringwithnorepeatingcharacters-j0xygxngn7",
      "weight": 100
    }
  ]
}
2020/03/21 04:18:00
votergolibrary
authorgolibrary
permlinkfindlongestsubstringwithnorepeatingcharacters-j0xygxngn7
weight10000 (100.00%)
Transaction InfoBlock #41835342/Trx 5a93ed5c474d7f53e8a2b4851782d7207e4fab1d
View Raw JSON Data
{
  "trx_id": "5a93ed5c474d7f53e8a2b4851782d7207e4fab1d",
  "block": 41835342,
  "trx_in_block": 24,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-21T04:18:00",
  "op": [
    "vote",
    {
      "voter": "golibrary",
      "author": "golibrary",
      "permlink": "findlongestsubstringwithnorepeatingcharacters-j0xygxngn7",
      "weight": 10000
    }
  ]
}
2020/03/21 04:12:12
parent authorgolibrary
parent permlinkfindlongestsubstringwithnorepeatingcharacters-j0xygxngn7
authorinnerhive
permlinkinnerhive-re-golibraryfindlongestsubstringwithnorepeatingcharacters-j0xygxngn7
title
bodyhttps://i.imgur.com/CBqCEo5.png<br><br>HIVE IS ALIVE!!!<br><br>JOIN US, YOU'LL HAVE EXACTLY THE SAME BALANCE AS YOU HAVE HERE ON STEEM WITHOUT THE CENTRALIZATION AND CENSORSHIP!!<br><br>https://hive.blog
json metadata
Transaction InfoBlock #41835227/Trx be6cd156801c3f1bd49019d6596c447f48b080ab
View Raw JSON Data
{
  "trx_id": "be6cd156801c3f1bd49019d6596c447f48b080ab",
  "block": 41835227,
  "trx_in_block": 5,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-21T04:12:12",
  "op": [
    "comment",
    {
      "parent_author": "golibrary",
      "parent_permlink": "findlongestsubstringwithnorepeatingcharacters-j0xygxngn7",
      "author": "innerhive",
      "permlink": "innerhive-re-golibraryfindlongestsubstringwithnorepeatingcharacters-j0xygxngn7",
      "title": "",
      "body": "https://i.imgur.com/CBqCEo5.png<br><br>HIVE IS ALIVE!!!<br><br>JOIN US, YOU'LL HAVE EXACTLY THE SAME BALANCE AS YOU HAVE HERE ON STEEM WITHOUT THE CENTRALIZATION AND CENSORSHIP!!<br><br>https://hive.blog",
      "json_metadata": ""
    }
  ]
}
2020/03/21 04:12:09
voterinnerhive
authorgolibrary
permlinkfindlongestsubstringwithnorepeatingcharacters-j0xygxngn7
weight1 (0.01%)
Transaction InfoBlock #41835226/Trx 1bbcb363521a97b4fbfd90be197fe2a7e8a30df7
View Raw JSON Data
{
  "trx_id": "1bbcb363521a97b4fbfd90be197fe2a7e8a30df7",
  "block": 41835226,
  "trx_in_block": 2,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-21T04:12:09",
  "op": [
    "vote",
    {
      "voter": "innerhive",
      "author": "golibrary",
      "permlink": "findlongestsubstringwithnorepeatingcharacters-j0xygxngn7",
      "weight": 1
    }
  ]
}
2020/03/21 04:12:00
authorgolibrary
permlinkfindlongestsubstringwithnorepeatingcharacters-j0xygxngn7
max accepted payout1000000.000 SBD
percent steem dollars10000
allow votestrue
allow curation rewardstrue
extensions[[0,{"beneficiaries":[{"account":"steempress","weight":1500}]}]]
Transaction InfoBlock #41835223/Trx dd6b958b5eee731060f99a8f7c2c168dbc877d6b
View Raw JSON Data
{
  "trx_id": "dd6b958b5eee731060f99a8f7c2c168dbc877d6b",
  "block": 41835223,
  "trx_in_block": 18,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-21T04:12:00",
  "op": [
    "comment_options",
    {
      "author": "golibrary",
      "permlink": "findlongestsubstringwithnorepeatingcharacters-j0xygxngn7",
      "max_accepted_payout": "1000000.000 SBD",
      "percent_steem_dollars": 10000,
      "allow_votes": true,
      "allow_curation_rewards": true,
      "extensions": [
        [
          0,
          {
            "beneficiaries": [
              {
                "account": "steempress",
                "weight": 1500
              }
            ]
          }
        ]
      ]
    }
  ]
}
2020/03/21 04:12:00
parent author
parent permlinksteempress
authorgolibrary
permlinkfindlongestsubstringwithnorepeatingcharacters-j0xygxngn7
titleFind longest substring with no repeating characters
body<center>https://www.golibrary.co/wp-content/uploads/2020/03/longest-substring.jpg</center> <br/><h3 id="problem-statement" data-id="0f3c185023ec811f417e671bc39b2ae2">Problem Statement</h3> &nbsp; <p data-id="4ca50dacd658243007f43b35d98105e0">Given a string, find the <strong>length of the longest substring</strong> which has <strong>no repeating characters</strong>.</p><br />&nbsp; <b>Example 1:</b> &nbsp; Input: String="aabccbb" Output: 3 Explanation: The longest substring without any repeating characters is "abc".<br />&nbsp; <b>Example 2:</b> &nbsp; Input: String="abbbb" Output: 2 Explanation: The longest substring without any repeating characters is "ab".<br />&nbsp; <b>Example 3:</b> &nbsp; Input: String="abccde" Output: 3 Explanation: Longest substrings without any repeating characters are "abc" &amp; "cde". &nbsp; <strong>Solution</strong> &nbsp; This problem follows the <strong>Sliding Window</strong> pattern and we can use a similar dynamic sliding window strategy as discussed in <a href="https://www.golibrary.co/find-length-of-longest-substring-with-no-more-than-k-distinct-characters/" target="_blank" rel="noopener noreferrer">Longest Substring with K Distinct Characters</a>. We can use a <strong>Map</strong> to remember the last index of each character we have processed. Whenever we get a repeating character we will shrink our sliding window to ensure that we always have distinct characters in the sliding window. We will find max window size in each pass and once the whole string is processed, the max window size is the total highest possible window size. &nbsp; &nbsp; <em><strong>Javascript code below:-</strong></em> &nbsp; &nbsp; <div class="wp-block-codemirror-blocks code-block alignwide"> <pre class="CodeMirror" data-setting="{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:true,&quot;lineWrapping&quot;:true,&quot;styleActiveLine&quot;:true,&quot;readOnly&quot;:false,&quot;align&quot;:&quot;wide&quot;}">&lt;script&gt; function non_repeat_substring(str) { let windowStart = 0, maxLength = 0, charIndexMap = {}; // try to extend the range [windowStart, windowEnd] for (let windowEnd = 0; windowEnd &lt; str.length; windowEnd++) { if (typeof charIndexMap[str[windowEnd]] !== 'undefined') { windowStart = Math.max(windowStart, charIndexMap[str[windowEnd]]+1); } charIndexMap[str[windowEnd]] = windowEnd; maxLength = Math.max(maxLength, windowEnd - windowStart + 1); } return maxLength; } document.write(`Length of the longest substring: ${non_repeat_substring('aabccbb')}&lt;br/&gt;`); document.write(`Length of the longest substring: ${non_repeat_substring('abbbb')}&lt;br/&gt;`); document.write(`Length of the longest substring: ${non_repeat_substring('abccde')}&lt;br/&gt;`); &lt;/script&gt;</pre> </div> &nbsp; &nbsp; <h4 id="time-complexity" data-id="4aee6881c21420310492cbdf7cb9003b">Time Complexity</h4> &nbsp; <p data-id="7b27085bde2f369842a064d52dc95b19">The time complexity of the above algorithm will be <strong>O(N) </strong>where <strong>‘N’</strong> is the number of characters in the input string.</p><br />&nbsp; <h4 id="space-complexity" data-id="4557d9eda0cfe746575b79994109e4b8">Space Complexity</h4> &nbsp; <p data-id="011aa1826fdf673b95c4aadf9b3d84c9">The space complexity of the algorithm will be <strong>O(K)</strong> where K is the number of distinct characters in the input string. This also means <strong>K&lt;=N,</strong> because in the worst case, the whole string might not have any repeating character so the entire string will be added to the <strong>Map</strong>. Having said that, since we can expect a fixed set of characters in the input string (e.g., 26 for English letters), we can say that the algorithm runs in fixed space <strong>O(1);</strong> in this case, we can use a fixed-size array instead of the <strong>Map</strong>.</p> <p data-id="011aa1826fdf673b95c4aadf9b3d84c9"></p><br />&nbsp; <br /><center><hr/><em>Posted from my blog with <a href='https://wordpress.org/plugins/steempress/'>SteemPress</a> : https://www.golibrary.co/find-longest-substring-with-no-repeating-characters/ </em><hr/></center>
json metadata{"community":"steempress","app":"steempress","image":["https://www.golibrary.co/wp-content/uploads/2020/03/longest-substring.jpg"],"tags":["steempress","steem","golibrary","technology","characters"],"canonical_url":"https://www.golibrary.co/find-longest-substring-with-no-repeating-characters/"}
Transaction InfoBlock #41835223/Trx dd6b958b5eee731060f99a8f7c2c168dbc877d6b
View Raw JSON Data
{
  "trx_id": "dd6b958b5eee731060f99a8f7c2c168dbc877d6b",
  "block": 41835223,
  "trx_in_block": 18,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-21T04:12:00",
  "op": [
    "comment",
    {
      "parent_author": "",
      "parent_permlink": "steempress",
      "author": "golibrary",
      "permlink": "findlongestsubstringwithnorepeatingcharacters-j0xygxngn7",
      "title": "Find longest substring with no repeating characters",
      "body": "<center>https://www.golibrary.co/wp-content/uploads/2020/03/longest-substring.jpg</center> <br/><h3 id=\"problem-statement\" data-id=\"0f3c185023ec811f417e671bc39b2ae2\">Problem Statement</h3>\r\n&nbsp;\r\n<p data-id=\"4ca50dacd658243007f43b35d98105e0\">Given a string, find the <strong>length of the longest substring</strong> which has <strong>no repeating characters</strong>.</p><br />&nbsp;\r\n<b>Example 1:</b>\r\n\r\n&nbsp;\r\n\r\nInput: String=\"aabccbb\"\r\n\r\nOutput: 3\r\n\r\nExplanation: The longest substring without any repeating characters is \"abc\".<br />&nbsp;\r\n\r\n<b>Example 2:</b>\r\n\r\n&nbsp;\r\n\r\nInput: String=\"abbbb\"\r\n\r\nOutput: 2\r\n\r\nExplanation: The longest substring without any repeating characters is \"ab\".<br />&nbsp;\r\n\r\n<b>Example 3:</b>\r\n\r\n&nbsp;\r\n\r\nInput: String=\"abccde\"\r\n\r\nOutput: 3\r\n\r\nExplanation: Longest substrings without any repeating characters are \"abc\" &amp; \"cde\".\r\n\r\n&nbsp;\r\n\r\n<strong>Solution</strong>\r\n\r\n&nbsp;\r\n\r\nThis problem follows the <strong>Sliding Window</strong> pattern and we can use a similar dynamic sliding window strategy as discussed in <a href=\"https://www.golibrary.co/find-length-of-longest-substring-with-no-more-than-k-distinct-characters/\" target=\"_blank\" rel=\"noopener noreferrer\">Longest Substring with K Distinct Characters</a>. We can use a <strong>Map</strong> to remember the last index of each character we have processed. Whenever we get a repeating character we will shrink our sliding window to ensure that we always have distinct characters in the sliding window. We will find max window size in each pass and once the whole string is processed, the max window size is the total highest possible window size.\r\n\r\n&nbsp;\r\n\r\n&nbsp;\r\n\r\n<em><strong>Javascript code below:-</strong></em>\r\n\r\n&nbsp;\r\n\r\n&nbsp;\r\n<div class=\"wp-block-codemirror-blocks code-block alignwide\">\r\n<pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:true,&quot;lineWrapping&quot;:true,&quot;styleActiveLine&quot;:true,&quot;readOnly&quot;:false,&quot;align&quot;:&quot;wide&quot;}\">&lt;script&gt;\r\nfunction non_repeat_substring(str) {\r\n  let windowStart = 0,\r\n    maxLength = 0,\r\n    charIndexMap = {};\r\n\r\n  // try to extend the range [windowStart, windowEnd]\r\n  for (let windowEnd = 0; windowEnd &lt; str.length; windowEnd++) {\r\n\r\n    if (typeof charIndexMap[str[windowEnd]] !== 'undefined') {\r\n      windowStart = Math.max(windowStart, charIndexMap[str[windowEnd]]+1);\r\n    }\r\n    charIndexMap[str[windowEnd]] = windowEnd;\r\n    maxLength = Math.max(maxLength, windowEnd - windowStart + 1);\r\n\r\n  }\r\n\r\n  return maxLength;\r\n}\r\n\r\ndocument.write(`Length of the longest substring: ${non_repeat_substring('aabccbb')}&lt;br/&gt;`);\r\ndocument.write(`Length of the longest substring: ${non_repeat_substring('abbbb')}&lt;br/&gt;`);\r\ndocument.write(`Length of the longest substring: ${non_repeat_substring('abccde')}&lt;br/&gt;`);\r\n&lt;/script&gt;</pre>\r\n</div>\r\n&nbsp;\r\n\r\n&nbsp;\r\n<h4 id=\"time-complexity\" data-id=\"4aee6881c21420310492cbdf7cb9003b\">Time Complexity</h4>\r\n&nbsp;\r\n<p data-id=\"7b27085bde2f369842a064d52dc95b19\">The time complexity of the above algorithm will be <strong>O(N) </strong>where <strong>‘N’</strong> is the number of characters in the input string.</p><br />&nbsp;\r\n\r\n<h4 id=\"space-complexity\" data-id=\"4557d9eda0cfe746575b79994109e4b8\">Space Complexity</h4>\r\n&nbsp;\r\n<p data-id=\"011aa1826fdf673b95c4aadf9b3d84c9\">The space complexity of the algorithm will be <strong>O(K)</strong> where K is the number of distinct characters in the input string. This also means <strong>K&lt;=N,</strong> because in the worst case, the whole string might not have any repeating character so the entire string will be added to the <strong>Map</strong>. Having said that, since we can expect a fixed set of characters in the input string (e.g., 26 for English letters), we can say that the algorithm runs in fixed space <strong>O(1);</strong> in this case, we can use a fixed-size array instead of the <strong>Map</strong>.</p>\r\n<p data-id=\"011aa1826fdf673b95c4aadf9b3d84c9\"></p><br />&nbsp; <br /><center><hr/><em>Posted from my blog with <a href='https://wordpress.org/plugins/steempress/'>SteemPress</a> : https://www.golibrary.co/find-longest-substring-with-no-repeating-characters/ </em><hr/></center> ",
      "json_metadata": "{\"community\":\"steempress\",\"app\":\"steempress\",\"image\":[\"https://www.golibrary.co/wp-content/uploads/2020/03/longest-substring.jpg\"],\"tags\":[\"steempress\",\"steem\",\"golibrary\",\"technology\",\"characters\"],\"canonical_url\":\"https://www.golibrary.co/find-longest-substring-with-no-repeating-characters/\"}"
    }
  ]
}
2020/03/20 03:41:18
votergreateye
authorgolibrary
permlinkfindingmaximumnumberoffruitsthatcanbekeptinonebasket-x4ceqm0t8q
weight500 (5.00%)
Transaction InfoBlock #41806401/Trx e3a81e72d61fd852c07444b00a79036012d3e1db
View Raw JSON Data
{
  "trx_id": "e3a81e72d61fd852c07444b00a79036012d3e1db",
  "block": 41806401,
  "trx_in_block": 10,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-20T03:41:18",
  "op": [
    "vote",
    {
      "voter": "greateye",
      "author": "golibrary",
      "permlink": "findingmaximumnumberoffruitsthatcanbekeptinonebasket-x4ceqm0t8q",
      "weight": 500
    }
  ]
}
2020/03/20 03:32:54
parent authorgolibrary
parent permlinkfindingmaximumnumberoffruitsthatcanbekeptinonebasket-x4ceqm0t8q
authorinnerhive
permlinkinnerhive-re-golibraryfindingmaximumnumberoffruitsthatcanbekeptinonebasket-x4ceqm0t8q
title
bodyhttps://i.imgur.com/CBqCEo5.png<br><br>Join the community in our migration to Hive, a community built blockchain for the community. All Steem account holders will receive equivalent stake on the new Hive blockchain.<br><br>Please [follow @innerhive on twitter](https://twitter.com/innerhive) for more information.
json metadata
Transaction InfoBlock #41806233/Trx 09e8fc0204855096e25d90c2bb3817670be74733
View Raw JSON Data
{
  "trx_id": "09e8fc0204855096e25d90c2bb3817670be74733",
  "block": 41806233,
  "trx_in_block": 43,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-20T03:32:54",
  "op": [
    "comment",
    {
      "parent_author": "golibrary",
      "parent_permlink": "findingmaximumnumberoffruitsthatcanbekeptinonebasket-x4ceqm0t8q",
      "author": "innerhive",
      "permlink": "innerhive-re-golibraryfindingmaximumnumberoffruitsthatcanbekeptinonebasket-x4ceqm0t8q",
      "title": "",
      "body": "https://i.imgur.com/CBqCEo5.png<br><br>Join the community in our migration to Hive, a community built blockchain for the community.  All Steem account holders will receive equivalent stake on the new Hive blockchain.<br><br>Please [follow @innerhive on twitter](https://twitter.com/innerhive) for more information.",
      "json_metadata": ""
    }
  ]
}
2020/03/20 03:32:54
voterinnerhive
authorgolibrary
permlinkfindingmaximumnumberoffruitsthatcanbekeptinonebasket-x4ceqm0t8q
weight1 (0.01%)
Transaction InfoBlock #41806233/Trx 6e1a368bc1a2a5969ea2cd98010d093a929fb09b
View Raw JSON Data
{
  "trx_id": "6e1a368bc1a2a5969ea2cd98010d093a929fb09b",
  "block": 41806233,
  "trx_in_block": 12,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-20T03:32:54",
  "op": [
    "vote",
    {
      "voter": "innerhive",
      "author": "golibrary",
      "permlink": "findingmaximumnumberoffruitsthatcanbekeptinonebasket-x4ceqm0t8q",
      "weight": 1
    }
  ]
}
2020/03/20 03:32:51
votertonimontana
authorgolibrary
permlinkfindingmaximumnumberoffruitsthatcanbekeptinonebasket-x4ceqm0t8q
weight726 (7.26%)
Transaction InfoBlock #41806232/Trx 4dbbd7825fcfdc930ff04696996faab2ed3ae40c
View Raw JSON Data
{
  "trx_id": "4dbbd7825fcfdc930ff04696996faab2ed3ae40c",
  "block": 41806232,
  "trx_in_block": 23,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-20T03:32:51",
  "op": [
    "vote",
    {
      "voter": "tonimontana",
      "author": "golibrary",
      "permlink": "findingmaximumnumberoffruitsthatcanbekeptinonebasket-x4ceqm0t8q",
      "weight": 726
    }
  ]
}
2020/03/20 03:32:48
authorgolibrary
permlinkfindingmaximumnumberoffruitsthatcanbekeptinonebasket-x4ceqm0t8q
max accepted payout1000000.000 SBD
percent steem dollars10000
allow votestrue
allow curation rewardstrue
extensions[[0,{"beneficiaries":[{"account":"steempress","weight":1500}]}]]
Transaction InfoBlock #41806231/Trx 5c77639053be0b15fa3428c3d2642d339c842211
View Raw JSON Data
{
  "trx_id": "5c77639053be0b15fa3428c3d2642d339c842211",
  "block": 41806231,
  "trx_in_block": 21,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-20T03:32:48",
  "op": [
    "comment_options",
    {
      "author": "golibrary",
      "permlink": "findingmaximumnumberoffruitsthatcanbekeptinonebasket-x4ceqm0t8q",
      "max_accepted_payout": "1000000.000 SBD",
      "percent_steem_dollars": 10000,
      "allow_votes": true,
      "allow_curation_rewards": true,
      "extensions": [
        [
          0,
          {
            "beneficiaries": [
              {
                "account": "steempress",
                "weight": 1500
              }
            ]
          }
        ]
      ]
    }
  ]
}
2020/03/20 03:32:48
parent author
parent permlinksteempress
authorgolibrary
permlinkfindingmaximumnumberoffruitsthatcanbekeptinonebasket-x4ceqm0t8q
titleFinding maximum number of fruits that can be kept in one basket
body<center>https://www.golibrary.co/wp-content/uploads/2020/03/sliding-window.jpeg</center> <br/><h3 id="problem-statement" data-id="0f3c185023ec811f417e671bc39b2ae2">Problem Statement </h3> &nbsp; <p data-id="eac6f850d54c4347136c2c02de3df582">Given an array of characters where each character represents a fruit tree, you are given <strong>two baskets</strong> and your goal is to put <strong>maximum number of fruits in each basket</strong>. The only restriction is that <strong>each basket can have only one type of fruit</strong>.</p> <p data-id="c381cff8df7bd3f7714d9fb798173353">You can start with any tree, but once you have started you can’t skip a tree. You will pick one fruit from each tree until you cannot, i.e., you will stop when you have to pick from a third fruit type.</p> &nbsp; <p data-id="4fe900651305e40723ba973e3ac27742">Write a function to return the maximum number of fruits in both the baskets.</p> &nbsp; <p data-id="0b7b29d7656d8d29ec3286a241de010e"><strong>Example 1: </strong></p> Input: Fruit=['A', 'B', 'C', 'A', 'C'] Output: 3 Explanation: We can put 2 'C' in one basket and one 'A' in the other from the subarray ['C', 'A', 'C'] <strong>Example 2:</strong> Input: Fruit=['A', 'B', 'C', 'B', 'B', 'C'] Output: 5 Explanation: We can put 3 'B' in one basket and two 'C' in the other basket.  This can be done if we start with the second letter: ['B', 'C', 'B', 'B', 'C'] &nbsp; &nbsp; <strong>Solution</strong> This problem follows the <strong>Sliding Window</strong> pattern and is quite similar to <a style="color: #000000;" href="#" target="_blank" rel="noopener noreferrer">Longest Substring with K Distinct Characters</a>. In this problem, we need to find the length of the longest subarray with no more than two distinct characters (or fruit types!). This transforms the current problem into <strong>Longest Substring with K Distinct Characters</strong> where K=2. &nbsp; &nbsp; <em><strong>Javascript code below:-</strong></em> &nbsp; <div class="wp-block-codemirror-blocks code-block alignwide"> <pre class="CodeMirror" data-setting="{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:true,&quot;lineWrapping&quot;:true,&quot;styleActiveLine&quot;:true,&quot;readOnly&quot;:false,&quot;align&quot;:&quot;wide&quot;}">function fruits_into_baskets(fruits) { let windowStart = 0, maxLength = 0, fruitFrequency = {}; // try to extend the range [windowStart, windowEnd] for (let windowEnd = 0; windowEnd &lt; fruits.length; windowEnd++) { const rightFruit = fruits[windowEnd]; // collect fruits/character // prepare a frequency map of characters by initializing the values for the character/fruit as key if (typeof fruitFrequency[rightFruit] === 'undefined') { fruitFrequency[rightFruit] = 0; } fruitFrequency[rightFruit] += 1; // shrink the sliding window, until we are left with '2' fruits in the fruit frequency dictionary while (Object.keys(fruitFrequency).length &gt; 2) { const leftFruit = fruits[windowStart]; fruitFrequency[leftFruit] -= 1; if (fruitFrequency[leftFruit] === 0) { delete fruitFrequency[leftFruit]; } windowStart += 1; // shrink the window } maxLength = Math.max(maxLength, windowEnd - windowStart + 1); } return maxLength; } document.write(`Maximum number of fruits: ${fruits_into_baskets(['A', 'B', 'C', 'A', 'C'])}&lt;br/&gt;`); document.write(`Maximum number of fruits: ${fruits_into_baskets(['A', 'B', 'C', 'B', 'B', 'C'])}&lt;br/&gt;`);</pre> </div> &nbsp; <strong>Steps</strong> <ul> <li>Loop through the array of fruits (character array) and prepare a frequency map of characters with their respective occurrence count in the array.</li> </ul> &nbsp; <ul> <li>Assort the fruits with maximum number of one type of fruit in one basket and maximum number of another type of fruit in another basket.  <ul> <li> To do this, use the fruit frequency map and check which character frequency is at least 2 (or more) and with each iteration keep shrinking the sliding window and store the maximum window length in <strong>maxLength.</strong></li> </ul> </li> </ul> &nbsp; <ul> <li>Return <strong>maxLength.</strong></li> </ul> &nbsp; &nbsp; &nbsp; <h4 id="time-complexity" data-id="4aee6881c21420310492cbdf7cb9003b">Time Complexity</h4> &nbsp; <p data-id="a360a93b5e307c8b88fcf84e8f64d31b">The time complexity of the above algorithm will be <strong>O(N)</strong> where ‘N’ is the number of characters in the input array. The outer <em><strong>for</strong> </em>loop runs for all characters and the inner <em><strong>while</strong> </em>loop processes each character only once, therefore the time complexity of the algorithm will be <strong>O(N+N)</strong> which is asymptotically equivalent to <strong>O(N)</strong>.</p> &nbsp; <h4 id="space-complexity" data-id="4557d9eda0cfe746575b79994109e4b8">Space Complexity</h4> &nbsp; <p data-id="47ea7def42b77b013e40805a8e7c5c88">The algorithm runs in constant space <strong>O(1)</strong> as there can be a maximum of three types of fruits stored in the frequency map.</p> &nbsp; <br /><center><hr/><em>Posted from my blog with <a href='https://wordpress.org/plugins/steempress/'>SteemPress</a> : https://www.golibrary.co/finding-maximum-number-of-fruits-that-can-be-kept-in-one-basket/ </em><hr/></center>
json metadata{"community":"steempress","app":"steempress","image":["https://www.golibrary.co/wp-content/uploads/2020/03/sliding-window.jpeg"],"tags":["steempress","steem","golibrary","technology","basket"],"canonical_url":"https://www.golibrary.co/finding-maximum-number-of-fruits-that-can-be-kept-in-one-basket/"}
Transaction InfoBlock #41806231/Trx 5c77639053be0b15fa3428c3d2642d339c842211
View Raw JSON Data
{
  "trx_id": "5c77639053be0b15fa3428c3d2642d339c842211",
  "block": 41806231,
  "trx_in_block": 21,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-20T03:32:48",
  "op": [
    "comment",
    {
      "parent_author": "",
      "parent_permlink": "steempress",
      "author": "golibrary",
      "permlink": "findingmaximumnumberoffruitsthatcanbekeptinonebasket-x4ceqm0t8q",
      "title": "Finding maximum number of fruits that can be kept in one basket",
      "body": "<center>https://www.golibrary.co/wp-content/uploads/2020/03/sliding-window.jpeg</center> <br/><h3 id=\"problem-statement\" data-id=\"0f3c185023ec811f417e671bc39b2ae2\">Problem Statement </h3>\r\n&nbsp;\r\n<p data-id=\"eac6f850d54c4347136c2c02de3df582\">Given an array of characters where each character represents a fruit tree, you are given <strong>two baskets</strong> and your goal is to put <strong>maximum number of fruits in each basket</strong>. The only restriction is that <strong>each basket can have only one type of fruit</strong>.</p>\r\n<p data-id=\"c381cff8df7bd3f7714d9fb798173353\">You can start with any tree, but once you have started you can’t skip a tree. You will pick one fruit from each tree until you cannot, i.e., you will stop when you have to pick from a third fruit type.</p>\r\n&nbsp;\r\n<p data-id=\"4fe900651305e40723ba973e3ac27742\">Write a function to return the maximum number of fruits in both the baskets.</p>\r\n&nbsp;\r\n<p data-id=\"0b7b29d7656d8d29ec3286a241de010e\"><strong>Example 1: </strong></p>\r\n\r\nInput: Fruit=['A', 'B', 'C', 'A', 'C']\r\n\r\nOutput: 3\r\n\r\nExplanation: We can put 2 'C' in one basket and one 'A' in the other from the subarray ['C', 'A', 'C']\r\n\r\n\r\n\r\n<strong>Example 2:</strong>\r\n\r\nInput: Fruit=['A', 'B', 'C', 'B', 'B', 'C']\r\n\r\nOutput: 5\r\n\r\nExplanation: We can put 3 'B' in one basket and two 'C' in the other basket. \r\n\r\nThis can be done if we start with the second letter: ['B', 'C', 'B', 'B', 'C']\r\n\r\n&nbsp;\r\n\r\n&nbsp;\r\n\r\n<strong>Solution</strong>\r\n\r\nThis problem follows the <strong>Sliding Window</strong> pattern and is quite similar to <a style=\"color: #000000;\" href=\"#\" target=\"_blank\" rel=\"noopener noreferrer\">Longest Substring with K Distinct Characters</a>. In this problem, we need to find the length of the longest subarray with no more than two distinct characters (or fruit types!). This transforms the current problem into <strong>Longest Substring with K Distinct Characters</strong> where K=2.\r\n\r\n&nbsp;\r\n\r\n&nbsp;\r\n\r\n<em><strong>Javascript code below:-</strong></em>\r\n\r\n&nbsp;\r\n<div class=\"wp-block-codemirror-blocks code-block alignwide\">\r\n<pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:true,&quot;lineWrapping&quot;:true,&quot;styleActiveLine&quot;:true,&quot;readOnly&quot;:false,&quot;align&quot;:&quot;wide&quot;}\">function fruits_into_baskets(fruits) {\r\n  let windowStart = 0,\r\n    maxLength = 0,\r\n    fruitFrequency = {};\r\n\r\n  // try to extend the range [windowStart, windowEnd]\r\n  for (let windowEnd = 0; windowEnd &lt; fruits.length; windowEnd++) {\r\n    const rightFruit = fruits[windowEnd];    // collect fruits/character\r\n\r\n    // prepare a frequency map of characters by initializing the values for the character/fruit as key\r\n    if (typeof fruitFrequency[rightFruit] === 'undefined') {\r\n      fruitFrequency[rightFruit] = 0;\r\n    }\r\n    fruitFrequency[rightFruit] += 1;\r\n\r\n    // shrink the sliding window, until we are left with '2' fruits in the fruit frequency dictionary\r\n    while (Object.keys(fruitFrequency).length &gt; 2) {\r\n      const leftFruit = fruits[windowStart];\r\n      fruitFrequency[leftFruit] -= 1;\r\n      if (fruitFrequency[leftFruit] === 0) {\r\n        delete fruitFrequency[leftFruit];\r\n      }\r\n      windowStart += 1; // shrink the window\r\n    }\r\n    maxLength = Math.max(maxLength, windowEnd - windowStart + 1);\r\n  }\r\n\r\n  return maxLength;\r\n}\r\n\r\n\r\ndocument.write(`Maximum number of fruits: ${fruits_into_baskets(['A', 'B', 'C', 'A', 'C'])}&lt;br/&gt;`);\r\ndocument.write(`Maximum number of fruits: ${fruits_into_baskets(['A', 'B', 'C', 'B', 'B', 'C'])}&lt;br/&gt;`);</pre>\r\n</div>\r\n&nbsp;\r\n\r\n<strong>Steps</strong>\r\n<ul>\r\n <li>Loop through the array of fruits (character array) and prepare a frequency map of characters with their respective occurrence count in the array.</li>\r\n</ul>\r\n&nbsp;\r\n<ul>\r\n <li>Assort the fruits with maximum number of one type of fruit in one basket and maximum number of another type of fruit in another basket. \r\n<ul>\r\n <li> To do this, use the fruit frequency map and check which character frequency is at least 2 (or more) and with each iteration keep shrinking the sliding window and store the maximum window length in <strong>maxLength.</strong></li>\r\n</ul>\r\n</li>\r\n</ul>\r\n&nbsp;\r\n<ul>\r\n <li>Return <strong>maxLength.</strong></li>\r\n</ul>\r\n&nbsp;\r\n\r\n&nbsp;\r\n\r\n&nbsp;\r\n<h4 id=\"time-complexity\" data-id=\"4aee6881c21420310492cbdf7cb9003b\">Time Complexity</h4>\r\n&nbsp;\r\n<p data-id=\"a360a93b5e307c8b88fcf84e8f64d31b\">The time complexity of the above algorithm will be <strong>O(N)</strong> where ‘N’ is the number of characters in the input array. The outer <em><strong>for</strong> </em>loop runs for all characters and the inner <em><strong>while</strong> </em>loop processes each character only once, therefore the time complexity of the algorithm will be <strong>O(N+N)</strong> which is asymptotically equivalent to <strong>O(N)</strong>.</p>\r\n&nbsp;\r\n<h4 id=\"space-complexity\" data-id=\"4557d9eda0cfe746575b79994109e4b8\">Space Complexity</h4>\r\n&nbsp;\r\n<p data-id=\"47ea7def42b77b013e40805a8e7c5c88\">The algorithm runs in constant space <strong>O(1)</strong> as there can be a maximum of three types of fruits stored in the frequency map.</p>\r\n&nbsp; <br /><center><hr/><em>Posted from my blog with <a href='https://wordpress.org/plugins/steempress/'>SteemPress</a> : https://www.golibrary.co/finding-maximum-number-of-fruits-that-can-be-kept-in-one-basket/ </em><hr/></center> ",
      "json_metadata": "{\"community\":\"steempress\",\"app\":\"steempress\",\"image\":[\"https://www.golibrary.co/wp-content/uploads/2020/03/sliding-window.jpeg\"],\"tags\":[\"steempress\",\"steem\",\"golibrary\",\"technology\",\"basket\"],\"canonical_url\":\"https://www.golibrary.co/finding-maximum-number-of-fruits-that-can-be-kept-in-one-basket/\"}"
    }
  ]
}
2020/03/19 00:18:00
votergolibrary
authorgolibrary
permlinkfindingmaximumsizesubarraywithsumkinagivenarray-l9bvm7k1ra
weight10000 (100.00%)
Transaction InfoBlock #41773582/Trx 1f86fa51214b14bceda7a1c846a065c95feb0af2
View Raw JSON Data
{
  "trx_id": "1f86fa51214b14bceda7a1c846a065c95feb0af2",
  "block": 41773582,
  "trx_in_block": 17,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-19T00:18:00",
  "op": [
    "vote",
    {
      "voter": "golibrary",
      "author": "golibrary",
      "permlink": "findingmaximumsizesubarraywithsumkinagivenarray-l9bvm7k1ra",
      "weight": 10000
    }
  ]
}
2020/03/19 00:17:36
parent author
parent permlinksteempress
authorgolibrary
permlinkfindingmaximumsizesubarraywithsumkinagivenarray-l9bvm7k1ra
titleFinding max sum of subarray with a given length in an array
body<center>https://www.golibrary.co/wp-content/uploads/2020/03/subarray-sum.png</center> <br/><h3 id="problem-statement" data-id="0f3c185023ec811f417e671bc39b2ae2">Problem Statement</h3> <p data-id="53407cb1d103ecabf6f1785cf8c7554a">Given an array of positive numbers and a positive number ‘k’, find the <strong>maximum sum of any contiguous subarray of size ‘k’</strong>.</p> &nbsp; <p data-id="0b7b29d7656d8d29ec3286a241de010e"><strong>Example 1:</strong></p> Input: [2, 1, 5, 1, 3, 2], k=3  Output: 9 Explanation: Subarray with maximum sum is [5, 1, 3]. &nbsp; &nbsp; <p data-id="0b7b29d7656d8d29ec3286a241de010e"><strong>Example 2:</strong></p> Input: [2, 3, 4, 1, 5], k=2  Output: 7 Explanation: Subarray with maximum sum is [3, 4]. <h3 id="try-it-yourself" data-id="091e53f55f3812664765f2ff8f3aff6d"></h3> &nbsp; <h3 id="solution" data-id="f69ad95ba722a9debe3d34a9dec8f95b">Solution</h3> A basic brute force solution will be to calculate the sum of all <strong>‘k’</strong> sized subarrays of the given array, to find the subarray with the highest sum. We can start from every index of the given array and add the next <strong>‘k’</strong> elements to find the sum of the subarray. Following is the visual representation of this algorithm for Example-1: &nbsp; <img class="size-full wp-image-2998" src="https://www.golibrary.co/wp-content/uploads/2020/03/subarray-sum.png" alt="subarray sum" width="843" height="492" /><br/> subarray sum depiction &nbsp; &nbsp; Javascript Code below (brute force approach):- &nbsp; &nbsp; <div class="wp-block-codemirror-blocks code-block alignwide"> <pre class="CodeMirror" data-setting="{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:true,&quot;lineWrapping&quot;:true,&quot;styleActiveLine&quot;:true,&quot;readOnly&quot;:false,&quot;align&quot;:&quot;wide&quot;}">&lt;script&gt; function max_sub_array_of_size_k(k, arr) { let maxSum = 0, windowSum = 0; // loop through start till array length - k for (i = 0; i &lt; arr.length - k + 1; i++) { windowSum = 0; // loop through i to i + k elements for (j = i; j &lt; i + k; j++) { windowSum += arr[j]; } maxSum = Math.max(maxSum, windowSum); } return maxSum; } document.write(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(3, [2, 1, 5, 1, 3, 2])}&lt;br/&gt;`); document.write(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(2, [2, 3, 4, 1, 5])}&lt;br/&gt;`); &lt;/script&gt; </pre> </div> &nbsp; &nbsp; The time complexity of the above algorithm will be <strong>O(N*K)</strong>, where <strong>‘N’</strong> is the total number of elements in the given array and K is the size of sub-array. The above solution works but isn't efficient for large data sets. It will fail and run out of time. We need a better solution. To solve such problems, we use a pattern called <strong>"sliding window pattern or mechanism"</strong> &nbsp; &nbsp; <h4 id="a-better-approach" data-id="2cdf66315d2c2a56f4edd8ce9be179bb">Sliding window mechanism</h4> &nbsp; <p data-id="581101dc38b16279e9eb58f9eaa3e0d8">If we observe closely, we realize that we can reuse the sum of previous sub-array at each point to calculate the sum of current sub-array a.k.a <strong>window</strong>. We consider each sub-array as a <strong>Sliding Window</strong> of size <strong>‘k’</strong>. To calculate the sum of the next sub-array, we need to slide the window ahead by one element. So to slide the window forward and calculate the sum of the new position of the sliding window, we need to do two things:</p> <ol data-id="27b891f85213769fc57d13aac390468a"> <li>Subtract the element going out of the sliding window i.e., subtract the first element of the window.</li> <li>Add the new element getting included in the sliding window i.e., the element coming right after the end of the window.</li> </ol> &nbsp; <p data-id="b67a035c1779640e66cb49bfb45dce88">This approach will save us from re-calculating the sum of the overlapping part of the sliding window. Here is what our algorithm will look like:</p> &nbsp; <div class="wp-block-codemirror-blocks code-block alignwide"> <pre class="CodeMirror" data-setting="{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:true,&quot;lineWrapping&quot;:true,&quot;styleActiveLine&quot;:true,&quot;readOnly&quot;:false,&quot;align&quot;:&quot;wide&quot;}">&lt;script&gt; function max_sub_array_of_size_k(k, arr) { var maxSum = 0; var windowStart = 0; var windowSum = 0; for (var windowEnd = 0; windowEnd &lt; arr.length; windowEnd++) { windowSum += arr[windowEnd]; if (windowEnd &gt;= k - 1) { maxSum = Math.max(maxSum, windowSum); windowSum -= arr[windowStart]; windowStart++; } } return maxSum; } document.write(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(3, [2, 1, 5, 1, 3, 2])}&lt;br/&gt;`); document.write(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(2, [2, 3, 4, 1, 5])}&lt;br/&gt;`); &lt;/script&gt;</pre> </div> <h4 data-id="4aee6881c21420310492cbdf7cb9003b"></h4> &nbsp; <h4 id="time-complexity" data-id="4aee6881c21420310492cbdf7cb9003b">Time Complexity </h4> <p data-id="f9c90e2b944bd92ebc0b1c2fccda303e">The time complexity of the above algorithm will be O(N).</p> &nbsp; <h4 id="space-complexity" data-id="4557d9eda0cfe746575b79994109e4b8">Space Complexity </h4> <p data-id="31c0baa71fdd532a3e7bbd7007cac80b">The algorithm runs in constant space O(1).</p> &nbsp; &nbsp; <br /><center><hr/><em>Posted from my blog with <a href='https://wordpress.org/plugins/steempress/'>SteemPress</a> : https://www.golibrary.co/finding-maximum-size-subarray-with-sum-k-in-a-given-array/ </em><hr/></center>
json metadata{"community":"steempress","app":"steempress","image":["https://www.golibrary.co/wp-content/uploads/2020/03/subarray-sum.png"],"tags":["steempress","steem","golibrary","technology","maximum"],"canonical_url":"https://www.golibrary.co/finding-maximum-size-subarray-with-sum-k-in-a-given-array/"}
Transaction InfoBlock #41773574/Trx f821c130dcf101bae161d7229c63e85eb3554278
View Raw JSON Data
{
  "trx_id": "f821c130dcf101bae161d7229c63e85eb3554278",
  "block": 41773574,
  "trx_in_block": 2,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-19T00:17:36",
  "op": [
    "comment",
    {
      "parent_author": "",
      "parent_permlink": "steempress",
      "author": "golibrary",
      "permlink": "findingmaximumsizesubarraywithsumkinagivenarray-l9bvm7k1ra",
      "title": "Finding max sum of subarray with a given length in an array",
      "body": "<center>https://www.golibrary.co/wp-content/uploads/2020/03/subarray-sum.png</center> <br/><h3 id=\"problem-statement\" data-id=\"0f3c185023ec811f417e671bc39b2ae2\">Problem Statement</h3>\r\n<p data-id=\"53407cb1d103ecabf6f1785cf8c7554a\">Given an array of positive numbers and a positive number ‘k’, find the <strong>maximum sum of any contiguous subarray of size ‘k’</strong>.</p>\r\n&nbsp;\r\n<p data-id=\"0b7b29d7656d8d29ec3286a241de010e\"><strong>Example 1:</strong></p>\r\nInput: [2, 1, 5, 1, 3, 2], k=3 \r\n\r\nOutput: 9\r\n\r\nExplanation: Subarray with maximum sum is [5, 1, 3].\r\n\r\n&nbsp;\r\n\r\n&nbsp;\r\n<p data-id=\"0b7b29d7656d8d29ec3286a241de010e\"><strong>Example 2:</strong></p>\r\nInput: [2, 3, 4, 1, 5], k=2 \r\n\r\nOutput: 7\r\n\r\nExplanation: Subarray with maximum sum is [3, 4].\r\n<h3 id=\"try-it-yourself\" data-id=\"091e53f55f3812664765f2ff8f3aff6d\"></h3>\r\n&nbsp;\r\n<h3 id=\"solution\" data-id=\"f69ad95ba722a9debe3d34a9dec8f95b\">Solution</h3>\r\nA basic brute force solution will be to calculate the sum of all <strong>‘k’</strong> sized subarrays of the given array, to find the subarray with the highest sum. We can start from every index of the given array and add the next <strong>‘k’</strong> elements to find the sum of the subarray. Following is the visual representation of this algorithm for Example-1:\r\n\r\n&nbsp;\r\n\r <img class=\"size-full wp-image-2998\" src=\"https://www.golibrary.co/wp-content/uploads/2020/03/subarray-sum.png\" alt=\"subarray sum\" width=\"843\" height=\"492\" /><br/> subarray sum depiction\r\n\r\n&nbsp;\r\n\r\n&nbsp;\r\n\r\nJavascript Code below (brute force approach):-\r\n\r\n&nbsp;\r\n\r\n&nbsp;\r\n<div class=\"wp-block-codemirror-blocks code-block alignwide\">\r\n<pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:true,&quot;lineWrapping&quot;:true,&quot;styleActiveLine&quot;:true,&quot;readOnly&quot;:false,&quot;align&quot;:&quot;wide&quot;}\">&lt;script&gt;\r\nfunction max_sub_array_of_size_k(k, arr) {\r\n  let maxSum = 0,\r\n    windowSum = 0;\r\n  // loop through start till array length - k\r\n  for (i = 0; i &lt; arr.length - k + 1; i++) {\r\n    windowSum = 0;\r\n    // loop through i to i + k elements\r\n    for (j = i; j &lt; i + k; j++) {\r\n      windowSum += arr[j];\r\n    }\r\n    maxSum = Math.max(maxSum, windowSum);\r\n  }\r\n  return maxSum;\r\n}\r\n\r\n\r\ndocument.write(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(3, [2, 1, 5, 1, 3, 2])}&lt;br/&gt;`);\r\ndocument.write(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(2, [2, 3, 4, 1, 5])}&lt;br/&gt;`);\r\n&lt;/script&gt;\r\n</pre>\r\n</div>\r\n&nbsp;\r\n\r\n&nbsp;\r\n\r\nThe time complexity of the above algorithm will be <strong>O(N*K)</strong>, where <strong>‘N’</strong> is the total number of elements in the given array and K is the size of sub-array.\r\n\r\nThe above solution works but isn't efficient for large data sets. It will fail and run out of time. We need a better solution.\r\n\r\nTo solve such problems, we use a pattern called <strong>\"sliding window pattern or mechanism\"</strong>\r\n\r\n&nbsp;\r\n\r\n&nbsp;\r\n<h4 id=\"a-better-approach\" data-id=\"2cdf66315d2c2a56f4edd8ce9be179bb\">Sliding window mechanism</h4>\r\n&nbsp;\r\n<p data-id=\"581101dc38b16279e9eb58f9eaa3e0d8\">If we observe closely, we realize that we can reuse the sum of previous sub-array at each point to calculate the sum of current sub-array a.k.a <strong>window</strong>. We consider each sub-array as a <strong>Sliding Window</strong> of size <strong>‘k’</strong>. To calculate the sum of the next sub-array, we need to slide the window ahead by one element. So to slide the window forward and calculate the sum of the new position of the sliding window, we need to do two things:</p>\r\n\r\n<ol data-id=\"27b891f85213769fc57d13aac390468a\">\r\n <li>Subtract the element going out of the sliding window i.e., subtract the first element of the window.</li>\r\n <li>Add the new element getting included in the sliding window i.e., the element coming right after the end of the window.</li>\r\n</ol>\r\n&nbsp;\r\n<p data-id=\"b67a035c1779640e66cb49bfb45dce88\">This approach will save us from re-calculating the sum of the overlapping part of the sliding window. Here is what our algorithm will look like:</p>\r\n&nbsp;\r\n<div class=\"wp-block-codemirror-blocks code-block alignwide\">\r\n<pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:true,&quot;lineWrapping&quot;:true,&quot;styleActiveLine&quot;:true,&quot;readOnly&quot;:false,&quot;align&quot;:&quot;wide&quot;}\">&lt;script&gt;\r\nfunction max_sub_array_of_size_k(k, arr) {\r\nvar maxSum = 0;\r\nvar windowStart = 0;\r\n\r\nvar windowSum = 0;\r\n\r\n\r\nfor (var windowEnd = 0; windowEnd &lt; arr.length; windowEnd++) {\r\nwindowSum += arr[windowEnd];\r\n\r\nif (windowEnd &gt;= k - 1) {\r\nmaxSum = Math.max(maxSum, windowSum);\r\nwindowSum -= arr[windowStart];\r\nwindowStart++;\r\n}\r\n}\r\n\r\nreturn maxSum;\r\n}\r\n\r\n\r\ndocument.write(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(3, [2, 1, 5, 1, 3, 2])}&lt;br/&gt;`);\r\ndocument.write(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(2, [2, 3, 4, 1, 5])}&lt;br/&gt;`);\r\n&lt;/script&gt;</pre>\r\n</div>\r\n<h4 data-id=\"4aee6881c21420310492cbdf7cb9003b\"></h4>\r\n&nbsp;\r\n<h4 id=\"time-complexity\" data-id=\"4aee6881c21420310492cbdf7cb9003b\">Time Complexity </h4>\r\n<p data-id=\"f9c90e2b944bd92ebc0b1c2fccda303e\">The time complexity of the above algorithm will be O(N).</p>\r\n&nbsp;\r\n<h4 id=\"space-complexity\" data-id=\"4557d9eda0cfe746575b79994109e4b8\">Space Complexity </h4>\r\n<p data-id=\"31c0baa71fdd532a3e7bbd7007cac80b\">The algorithm runs in constant space O(1).</p>\r\n&nbsp;\r\n\r\n&nbsp; <br /><center><hr/><em>Posted from my blog with <a href='https://wordpress.org/plugins/steempress/'>SteemPress</a> : https://www.golibrary.co/finding-maximum-size-subarray-with-sum-k-in-a-given-array/ </em><hr/></center> ",
      "json_metadata": "{\"community\":\"steempress\",\"app\":\"steempress\",\"image\":[\"https://www.golibrary.co/wp-content/uploads/2020/03/subarray-sum.png\"],\"tags\":[\"steempress\",\"steem\",\"golibrary\",\"technology\",\"maximum\"],\"canonical_url\":\"https://www.golibrary.co/finding-maximum-size-subarray-with-sum-k-in-a-given-array/\"}"
    }
  ]
}
2020/03/18 13:32:33
voterpayroll
authorgolibrary
permlinklengthofsmallestsubarraywithasumgreaterthanorequaltos-51dajsyr1f
weight100 (1.00%)
Transaction InfoBlock #41760689/Trx 4b0d8f62fb75b28f5f4f65519326d56e56d26254
View Raw JSON Data
{
  "trx_id": "4b0d8f62fb75b28f5f4f65519326d56e56d26254",
  "block": 41760689,
  "trx_in_block": 25,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-18T13:32:33",
  "op": [
    "vote",
    {
      "voter": "payroll",
      "author": "golibrary",
      "permlink": "lengthofsmallestsubarraywithasumgreaterthanorequaltos-51dajsyr1f",
      "weight": 100
    }
  ]
}
2020/03/18 13:11:15
parent authorgolibrary
parent permlinklengthofsmallestsubarraywithasumgreaterthanorequaltos-51dajsyr1f
authorflorianopolis
permlinkyz5bl2qvfx
title
body He said, ***'Stop doing wrong things and turn back to God! The kingdom of heaven is almost here.***'(Matthew 3:2) ## *Bro. Eli Challenges Atheism Belief, There is No God* Watch the Video below to know the Answer... ***(Sorry for sending this comment. We are not looking for our self profit, our intentions is to preach the words of God in any means possible.)*** https://youtu.be/QqkuNRO4Bt4 Comment what you understand of our Youtube Video to receive our full votes. We have 30,000 #SteemPower. It's our little way to **Thank you, our beloved friend.** Check our [Discord Chat](https://discord.gg/vzHFNd6) Join our Official Community: https://steemit.com/created/hive-182074
json metadata
Transaction InfoBlock #41760265/Trx 0e0f003361bf2ffbe29429f84c789279b8f2e60a
View Raw JSON Data
{
  "trx_id": "0e0f003361bf2ffbe29429f84c789279b8f2e60a",
  "block": 41760265,
  "trx_in_block": 3,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-18T13:11:15",
  "op": [
    "comment",
    {
      "parent_author": "golibrary",
      "parent_permlink": "lengthofsmallestsubarraywithasumgreaterthanorequaltos-51dajsyr1f",
      "author": "florianopolis",
      "permlink": "yz5bl2qvfx",
      "title": "",
      "body": "\nHe said, ***'Stop doing wrong things and turn back to God! The kingdom of heaven is almost here.***'(Matthew 3:2) \n##  *Bro. Eli Challenges Atheism Belief, There is No God*\nWatch the Video below to know the Answer...\n***(Sorry for sending this comment. We are not looking for our self profit, our intentions is to preach the words of God in any means possible.)***\nhttps://youtu.be/QqkuNRO4Bt4\nComment what you understand of our Youtube Video to receive our full votes. We have 30,000 #SteemPower. It's our little way to **Thank you, our beloved friend.**  \nCheck our [Discord Chat](https://discord.gg/vzHFNd6) \nJoin our Official Community: https://steemit.com/created/hive-182074\n",
      "json_metadata": ""
    }
  ]
}
2020/03/18 13:11:15
voterflorianopolis
authorgolibrary
permlinklengthofsmallestsubarraywithasumgreaterthanorequaltos-51dajsyr1f
weight100 (1.00%)
Transaction InfoBlock #41760265/Trx cdd05ddf073cada11f762b17accba49b553fbf70
View Raw JSON Data
{
  "trx_id": "cdd05ddf073cada11f762b17accba49b553fbf70",
  "block": 41760265,
  "trx_in_block": 0,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-18T13:11:15",
  "op": [
    "vote",
    {
      "voter": "florianopolis",
      "author": "golibrary",
      "permlink": "lengthofsmallestsubarraywithasumgreaterthanorequaltos-51dajsyr1f",
      "weight": 100
    }
  ]
}
2020/03/18 13:06:06
voteryuxi
authorgolibrary
permlinklengthofsmallestsubarraywithasumgreaterthanorequaltos-51dajsyr1f
weight1895 (18.95%)
Transaction InfoBlock #41760163/Trx ad034fdb436916618d5ba8bded91634aeac8846d
View Raw JSON Data
{
  "trx_id": "ad034fdb436916618d5ba8bded91634aeac8846d",
  "block": 41760163,
  "trx_in_block": 5,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-18T13:06:06",
  "op": [
    "vote",
    {
      "voter": "yuxi",
      "author": "golibrary",
      "permlink": "lengthofsmallestsubarraywithasumgreaterthanorequaltos-51dajsyr1f",
      "weight": 1895
    }
  ]
}
2020/03/18 13:03:00
votertonimontana
authorgolibrary
permlinklengthofsmallestsubarraywithasumgreaterthanorequaltos-51dajsyr1f
weight726 (7.26%)
Transaction InfoBlock #41760102/Trx f81e28c108bf4e71723d26aee00b06e76613c9a3
View Raw JSON Data
{
  "trx_id": "f81e28c108bf4e71723d26aee00b06e76613c9a3",
  "block": 41760102,
  "trx_in_block": 26,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-18T13:03:00",
  "op": [
    "vote",
    {
      "voter": "tonimontana",
      "author": "golibrary",
      "permlink": "lengthofsmallestsubarraywithasumgreaterthanorequaltos-51dajsyr1f",
      "weight": 726
    }
  ]
}
2020/03/18 13:02:57
authorgolibrary
permlinklengthofsmallestsubarraywithasumgreaterthanorequaltos-51dajsyr1f
max accepted payout1000000.000 SBD
percent steem dollars10000
allow votestrue
allow curation rewardstrue
extensions[[0,{"beneficiaries":[{"account":"steempress","weight":1500}]}]]
Transaction InfoBlock #41760101/Trx b6901141c1e2a531a1c4effd8bb745e83305f816
View Raw JSON Data
{
  "trx_id": "b6901141c1e2a531a1c4effd8bb745e83305f816",
  "block": 41760101,
  "trx_in_block": 14,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-18T13:02:57",
  "op": [
    "comment_options",
    {
      "author": "golibrary",
      "permlink": "lengthofsmallestsubarraywithasumgreaterthanorequaltos-51dajsyr1f",
      "max_accepted_payout": "1000000.000 SBD",
      "percent_steem_dollars": 10000,
      "allow_votes": true,
      "allow_curation_rewards": true,
      "extensions": [
        [
          0,
          {
            "beneficiaries": [
              {
                "account": "steempress",
                "weight": 1500
              }
            ]
          }
        ]
      ]
    }
  ]
}
2020/03/18 13:02:57
parent author
parent permlinksteempress
authorgolibrary
permlinklengthofsmallestsubarraywithasumgreaterthanorequaltos-51dajsyr1f
titleLength of smallest subarray with a sum greater than or equal to S
body<center>https://www.golibrary.co/wp-content/uploads/2020/03/minsum-subarray.png</center> <br/><h3 id="problem-statement" data-id="0f3c185023ec811f417e671bc39b2ae2">Problem Statement </h3> &nbsp; <p data-id="c2ae1924171affab35d9a4c8e8b68a29">Given an array of positive numbers and a positive number ‘S’, find the length of the <strong>smallest contiguous subarray whose sum is greater than or equal to ‘S’</strong>. Return 0, if no such subarray exists.</p> &nbsp; <p data-id="0b7b29d7656d8d29ec3286a241de010e"><strong>Example 1:</strong></p> Input: [2, 1, 5, 2, 3, 2], S=7  Output: 2 Explanation: The smallest subarray with a sum great than or equal to '7' is [5, 2]. &nbsp; &nbsp; <p data-id="2be7ab20c80a99b42fc79400ca3f36ea"><strong>Example 2:</strong></p> Input: [2, 1, 5, 2, 8], S=7  Output: 1 Explanation: The smallest subarray with a sum greater than or equal to '7' is [8]. &nbsp; &nbsp; <strong>Example 3:</strong> &nbsp; Input: [3, 4, 1, 1, 6], S=8  Output: 3 Explanation: Smallest subarrays with a sum greater than or equal to '8' are [3, 4, 1] or [1, 1, 6]. &nbsp; One simple solution is the brute force solution as seen in the previous <a style="background-color: #ffffff; color: #000000;" href="https://www.golibrary.co/finding-maximum-size-subarray-with-sum-k-in-a-given-array/" target="_blank" rel="noopener noreferrer">blog</a> <p data-id="2be7ab20c80a99b42fc79400ca3f36ea">but it's not effective, so this problem is another example of sliding window pattern and can be solved using the same approach as before.</p> <p data-id="2be7ab20c80a99b42fc79400ca3f36ea"></p> <p data-id="2be7ab20c80a99b42fc79400ca3f36ea"><strong>Efficient solution:</strong></p> <p data-id="6211dd446dd29e98bde94544099e4531">This problem follows the <strong>Sliding Window</strong> pattern and we can use a similar strategy as discussed in <a style="background-color: #ffffff; color: #000000;" href="https://www.golibrary.co/finding-maximum-size-subarray-with-sum-k-in-a-given-array/" target="_blank" rel="noopener noreferrer">Maximum Sum Subarray of Size K</a>. There is one difference though: in this problem, the size of the sliding window is not fixed. Here is how we will solve this problem:</p> <p data-id="6211dd446dd29e98bde94544099e4531"></p> <ul data-id="79f1f6ea43e1cdc1f0e2a03fa33fa803"> <li>First, we will add-up elements from the beginning of the array until their sum becomes greater than or equal to ‘S’.</li> </ul> &nbsp; <ul data-id="79f1f6ea43e1cdc1f0e2a03fa33fa803"> <li>These elements will constitute our sliding window. We are asked to find the smallest such window having a sum greater than or equal to ‘S’. We will remember the length of this window as the smallest window so far.</li> </ul> &nbsp; <ul data-id="79f1f6ea43e1cdc1f0e2a03fa33fa803"> <li>After this, we will keep adding one element in the sliding window (i.e. slide the window ahead), in a stepwise fashion.</li> </ul> &nbsp; <ul data-id="79f1f6ea43e1cdc1f0e2a03fa33fa803"> <li>In each step, we will also try to shrink the window from the beginning. We will shrink the window until the window’s sum is smaller than ‘S’ again. This is needed as we intend to find the smallest window. This shrinking will also happen in multiple steps; in each step we will do two things:</li> </ul> &nbsp; <ul> <li style="list-style-type: none;"> <ul> <li>Check if the current window length is the smallest so far, and if so, remember its length.</li> <li>Subtract the first element of the window from the running sum to shrink the sliding window.</li> </ul> </li> </ul> &nbsp; <p data-id="6436a01e43d6413c20cae1fec9a4332e">Here is the visual representation of this algorithm for the Example-1</p> <img class="size-full wp-image-3012" src="https://www.golibrary.co/wp-content/uploads/2020/03/minsum-subarray.png" alt="minsum-subarray" width="844" height="543" /><br/> minsum-subarray <p data-id="2be7ab20c80a99b42fc79400ca3f36ea"> Javascript code below:-</p> &nbsp; <div class="wp-block-codemirror-blocks code-block alignwide"> <pre class="CodeMirror" data-setting="{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:true,&quot;lineWrapping&quot;:true,&quot;styleActiveLine&quot;:true,&quot;readOnly&quot;:false,&quot;align&quot;:&quot;wide&quot;}">&lt;script&gt; const smallest_subarray_with_given_sum = function(s, arr) { // TODO: Write your code here var windowStart = 0; var minLength = Number.MAX_SAFE_INTEGER; var windowSum = 0; for (var windowEnd = 0; windowEnd &lt; arr.length; windowEnd++) { windowSum += arr[windowEnd]; while (windowSum &gt;= s) { minLength = Math.min(minLength, windowEnd - windowStart + 1); windowSum -= arr[windowStart]; windowStart++; } } if (minLength === Number.MAX_SAFE_INTEGER) return 0; return minLength; }; document.write(`Smallest subarray length: ${smallest_subarray_with_given_sum(7, [2, 1, 5, 2, 3, 2])}&lt;br/&gt;`); document.write(`Smallest subarray length: ${smallest_subarray_with_given_sum(7, [2, 1, 5, 2, 8])}&lt;br/&gt;`); document.write(`Smallest subarray length: ${smallest_subarray_with_given_sum(8, [3, 4, 1, 1, 6])}&lt;br/&gt;`); &lt;/script&gt;</pre> </div> <h4 data-id="4aee6881c21420310492cbdf7cb9003b"></h4> &nbsp; <h4 data-id="4aee6881c21420310492cbdf7cb9003b"></h4> <h4 id="time-complexity" data-id="4aee6881c21420310492cbdf7cb9003b">Time Complexity </h4> &nbsp; <p data-id="5c1c20bb61f8dc233626a1928c693c2c">The time complexity of the above algorithm will be O(N)O(N). The outer <em>for</em> loop runs for all elements and the inner <em>while</em> loop processes each element only once, therefore the time complexity of the algorithm will be<strong> O(N+N)</strong> which is asymptotically equivalent to <strong>O(N).</strong></p> &nbsp; <h4 id="space-complexity" data-id="4557d9eda0cfe746575b79994109e4b8">Space Complexity </h4> &nbsp; <p data-id="31c0baa71fdd532a3e7bbd7007cac80b">The algorithm runs in constant space <strong>O(1).</strong></p> <p data-id="31c0baa71fdd532a3e7bbd7007cac80b"></p> <p data-id="31c0baa71fdd532a3e7bbd7007cac80b"></p> <br /><center><hr/><em>Posted from my blog with <a href='https://wordpress.org/plugins/steempress/'>SteemPress</a> : https://www.golibrary.co/length-smallest-subarray-with-a-given-sum/ </em><hr/></center>
json metadata{"community":"steempress","app":"steempress","image":["https://www.golibrary.co/wp-content/uploads/2020/03/minsum-subarray.png"],"tags":["steempress","steem","golibrary","technology","array"],"canonical_url":"https://www.golibrary.co/length-smallest-subarray-with-a-given-sum/"}
Transaction InfoBlock #41760101/Trx b6901141c1e2a531a1c4effd8bb745e83305f816
View Raw JSON Data
{
  "trx_id": "b6901141c1e2a531a1c4effd8bb745e83305f816",
  "block": 41760101,
  "trx_in_block": 14,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-18T13:02:57",
  "op": [
    "comment",
    {
      "parent_author": "",
      "parent_permlink": "steempress",
      "author": "golibrary",
      "permlink": "lengthofsmallestsubarraywithasumgreaterthanorequaltos-51dajsyr1f",
      "title": "Length of smallest subarray with a sum greater than or equal to S",
      "body": "<center>https://www.golibrary.co/wp-content/uploads/2020/03/minsum-subarray.png</center> <br/><h3 id=\"problem-statement\" data-id=\"0f3c185023ec811f417e671bc39b2ae2\">Problem Statement </h3>\r\n&nbsp;\r\n<p data-id=\"c2ae1924171affab35d9a4c8e8b68a29\">Given an array of positive numbers and a positive number ‘S’, find the length of the <strong>smallest contiguous subarray whose sum is greater than or equal to ‘S’</strong>. Return 0, if no such subarray exists.</p>\r\n&nbsp;\r\n<p data-id=\"0b7b29d7656d8d29ec3286a241de010e\"><strong>Example 1:</strong></p>\r\nInput: [2, 1, 5, 2, 3, 2], S=7 \r\n\r\nOutput: 2\r\n\r\nExplanation: The smallest subarray with a sum great than or equal to '7' is [5, 2].\r\n\r\n&nbsp;\r\n\r\n&nbsp;\r\n<p data-id=\"2be7ab20c80a99b42fc79400ca3f36ea\"><strong>Example 2:</strong></p>\r\nInput: [2, 1, 5, 2, 8], S=7 \r\n\r\nOutput: 1\r\n\r\nExplanation: The smallest subarray with a sum greater than or equal to '7' is [8].\r\n\r\n&nbsp;\r\n\r\n&nbsp;\r\n\r\n<strong>Example 3:</strong>\r\n\r\n&nbsp;\r\n\r\nInput: [3, 4, 1, 1, 6], S=8 \r\n\r\nOutput: 3\r\n\r\nExplanation: Smallest subarrays with a sum greater than or equal to '8' are [3, 4, 1] or [1, 1, 6].\r\n\r\n&nbsp;\r\n\r\nOne simple solution is the brute force solution as seen in the previous <a style=\"background-color: #ffffff; color: #000000;\" href=\"https://www.golibrary.co/finding-maximum-size-subarray-with-sum-k-in-a-given-array/\" target=\"_blank\" rel=\"noopener noreferrer\">blog</a>\r\n<p data-id=\"2be7ab20c80a99b42fc79400ca3f36ea\">but it's not effective, so this problem is another example of sliding window pattern and can be solved using the same approach as before.</p>\r\n<p data-id=\"2be7ab20c80a99b42fc79400ca3f36ea\"></p>\r\n<p data-id=\"2be7ab20c80a99b42fc79400ca3f36ea\"><strong>Efficient solution:</strong></p>\r\n<p data-id=\"6211dd446dd29e98bde94544099e4531\">This problem follows the <strong>Sliding Window</strong> pattern and we can use a similar strategy as discussed in <a style=\"background-color: #ffffff; color: #000000;\" href=\"https://www.golibrary.co/finding-maximum-size-subarray-with-sum-k-in-a-given-array/\" target=\"_blank\" rel=\"noopener noreferrer\">Maximum Sum Subarray of Size K</a>. There is one difference though: in this problem, the size of the sliding window is not fixed. Here is how we will solve this problem:</p>\r\n<p data-id=\"6211dd446dd29e98bde94544099e4531\"></p>\r\n\r\n<ul data-id=\"79f1f6ea43e1cdc1f0e2a03fa33fa803\">\r\n <li>First, we will add-up elements from the beginning of the array until their sum becomes greater than or equal to ‘S’.</li>\r\n</ul>\r\n&nbsp;\r\n<ul data-id=\"79f1f6ea43e1cdc1f0e2a03fa33fa803\">\r\n <li>These elements will constitute our sliding window. We are asked to find the smallest such window having a sum greater than or equal to ‘S’. We will remember the length of this window as the smallest window so far.</li>\r\n</ul>\r\n&nbsp;\r\n<ul data-id=\"79f1f6ea43e1cdc1f0e2a03fa33fa803\">\r\n <li>After this, we will keep adding one element in the sliding window (i.e. slide the window ahead), in a stepwise fashion.</li>\r\n</ul>\r\n&nbsp;\r\n<ul data-id=\"79f1f6ea43e1cdc1f0e2a03fa33fa803\">\r\n <li>In each step, we will also try to shrink the window from the beginning. We will shrink the window until the window’s sum is smaller than ‘S’ again. This is needed as we intend to find the smallest window. This shrinking will also happen in multiple steps; in each step we will do two things:</li>\r\n</ul>\r\n&nbsp;\r\n<ul>\r\n <li style=\"list-style-type: none;\">\r\n<ul>\r\n <li>Check if the current window length is the smallest so far, and if so, remember its length.</li>\r\n <li>Subtract the first element of the window from the running sum to shrink the sliding window.</li>\r\n</ul>\r\n</li>\r\n</ul>\r\n&nbsp;\r\n<p data-id=\"6436a01e43d6413c20cae1fec9a4332e\">Here is the visual representation of this algorithm for the Example-1</p>\r\n\r\n\r <img class=\"size-full wp-image-3012\" src=\"https://www.golibrary.co/wp-content/uploads/2020/03/minsum-subarray.png\" alt=\"minsum-subarray\" width=\"844\" height=\"543\" /><br/> minsum-subarray\r\n<p data-id=\"2be7ab20c80a99b42fc79400ca3f36ea\">\r\n\r\n\r\nJavascript code below:-</p>\r\n&nbsp;\r\n<div class=\"wp-block-codemirror-blocks code-block alignwide\">\r\n<pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:true,&quot;lineWrapping&quot;:true,&quot;styleActiveLine&quot;:true,&quot;readOnly&quot;:false,&quot;align&quot;:&quot;wide&quot;}\">&lt;script&gt;\r\nconst smallest_subarray_with_given_sum = function(s, arr) {\r\n  // TODO: Write your code here\r\n  var windowStart = 0;\r\n  var minLength = Number.MAX_SAFE_INTEGER;\r\n  var windowSum = 0;\r\n\r\n  for (var windowEnd = 0; windowEnd &lt; arr.length; windowEnd++) {\r\n    windowSum += arr[windowEnd];\r\n\r\n    while (windowSum &gt;= s) {\r\n      minLength = Math.min(minLength, windowEnd - windowStart + 1);\r\n      windowSum -= arr[windowStart];\r\n      windowStart++;\r\n    }\r\n  }\r\n\r\n  if (minLength === Number.MAX_SAFE_INTEGER)\r\n    return 0;\r\n  \r\n  return minLength;\r\n};\r\n\r\n\r\ndocument.write(`Smallest subarray length: ${smallest_subarray_with_given_sum(7, [2, 1, 5, 2, 3, 2])}&lt;br/&gt;`);\r\ndocument.write(`Smallest subarray length: ${smallest_subarray_with_given_sum(7, [2, 1, 5, 2, 8])}&lt;br/&gt;`);\r\ndocument.write(`Smallest subarray length: ${smallest_subarray_with_given_sum(8, [3, 4, 1, 1, 6])}&lt;br/&gt;`);\r\n&lt;/script&gt;</pre>\r\n</div>\r\n<h4 data-id=\"4aee6881c21420310492cbdf7cb9003b\"></h4>\r\n&nbsp;\r\n<h4 data-id=\"4aee6881c21420310492cbdf7cb9003b\"></h4>\r\n<h4 id=\"time-complexity\" data-id=\"4aee6881c21420310492cbdf7cb9003b\">Time Complexity </h4>\r\n&nbsp;\r\n<p data-id=\"5c1c20bb61f8dc233626a1928c693c2c\">The time complexity of the above algorithm will be O(N)O(N). The outer <em>for</em> loop runs for all elements and the inner <em>while</em> loop processes each element only once, therefore the time complexity of the algorithm will be<strong> O(N+N)</strong> which is asymptotically equivalent to <strong>O(N).</strong></p>\r\n&nbsp;\r\n<h4 id=\"space-complexity\" data-id=\"4557d9eda0cfe746575b79994109e4b8\">Space Complexity </h4>\r\n&nbsp;\r\n<p data-id=\"31c0baa71fdd532a3e7bbd7007cac80b\">The algorithm runs in constant space <strong>O(1).</strong></p>\r\n<p data-id=\"31c0baa71fdd532a3e7bbd7007cac80b\"></p>\r\n<p data-id=\"31c0baa71fdd532a3e7bbd7007cac80b\"></p> <br /><center><hr/><em>Posted from my blog with <a href='https://wordpress.org/plugins/steempress/'>SteemPress</a> : https://www.golibrary.co/length-smallest-subarray-with-a-given-sum/ </em><hr/></center> ",
      "json_metadata": "{\"community\":\"steempress\",\"app\":\"steempress\",\"image\":[\"https://www.golibrary.co/wp-content/uploads/2020/03/minsum-subarray.png\"],\"tags\":[\"steempress\",\"steem\",\"golibrary\",\"technology\",\"array\"],\"canonical_url\":\"https://www.golibrary.co/length-smallest-subarray-with-a-given-sum/\"}"
    }
  ]
}
2020/03/17 12:01:42
parent authorgolibrary
parent permlinkfindingmaximumsizesubarraywithsumkinagivenarray-l9bvm7k1ra
authorflorianopolis
permlinkxj1s851odu
title
body He said, ***'Stop doing wrong things and turn back to God! The kingdom of heaven is almost here.***'(Matthew 3:2) ## *Bro. Eli Challenges Atheism Belief, There is No God* Watch the Video below to know the Answer... ***(Sorry for sending this comment. We are not looking for our self profit, our intentions is to preach the words of God in any means possible.)*** https://youtu.be/QqkuNRO4Bt4 Comment what you understand of our Youtube Video to receive our full votes. We have 30,000 #SteemPower. It's our little way to **Thank you, our beloved friend.** Check our [Discord Chat](https://discord.gg/vzHFNd6) Join our Official Community: https://steemit.com/created/hive-182074
json metadata
Transaction InfoBlock #41730122/Trx ddec1c814efc4d99075d701e50e8274918b14a13
View Raw JSON Data
{
  "trx_id": "ddec1c814efc4d99075d701e50e8274918b14a13",
  "block": 41730122,
  "trx_in_block": 45,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-17T12:01:42",
  "op": [
    "comment",
    {
      "parent_author": "golibrary",
      "parent_permlink": "findingmaximumsizesubarraywithsumkinagivenarray-l9bvm7k1ra",
      "author": "florianopolis",
      "permlink": "xj1s851odu",
      "title": "",
      "body": "\nHe said, ***'Stop doing wrong things and turn back to God! The kingdom of heaven is almost here.***'(Matthew 3:2) \n##  *Bro. Eli Challenges Atheism Belief, There is No God*\nWatch the Video below to know the Answer...\n***(Sorry for sending this comment. We are not looking for our self profit, our intentions is to preach the words of God in any means possible.)***\nhttps://youtu.be/QqkuNRO4Bt4\nComment what you understand of our Youtube Video to receive our full votes. We have 30,000 #SteemPower. It's our little way to **Thank you, our beloved friend.**  \nCheck our [Discord Chat](https://discord.gg/vzHFNd6) \nJoin our Official Community: https://steemit.com/created/hive-182074\n",
      "json_metadata": ""
    }
  ]
}
2020/03/17 12:01:42
voterflorianopolis
authorgolibrary
permlinkfindingmaximumsizesubarraywithsumkinagivenarray-l9bvm7k1ra
weight100 (1.00%)
Transaction InfoBlock #41730122/Trx 0c7bcbe55852b867b89f376624ab5f64214a4bc8
View Raw JSON Data
{
  "trx_id": "0c7bcbe55852b867b89f376624ab5f64214a4bc8",
  "block": 41730122,
  "trx_in_block": 44,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-17T12:01:42",
  "op": [
    "vote",
    {
      "voter": "florianopolis",
      "author": "golibrary",
      "permlink": "findingmaximumsizesubarraywithsumkinagivenarray-l9bvm7k1ra",
      "weight": 100
    }
  ]
}
2020/03/17 11:57:15
parent author
parent permlinksteempress
authorgolibrary
permlinkfindingmaximumsizesubarraywithsumkinagivenarray-l9bvm7k1ra
titleFinding maximum size subarray with sum K in a given array
body<center>https://www.golibrary.co/wp-content/uploads/2020/03/subarray-sum.png</center> <br/><h3 id="problem-statement" data-id="0f3c185023ec811f417e671bc39b2ae2">Problem Statement</h3> <p data-id="53407cb1d103ecabf6f1785cf8c7554a">Given an array of positive numbers and a positive number ‘k’, find the <strong>maximum sum of any contiguous subarray of size ‘k’</strong>.</p> <p data-id="53407cb1d103ecabf6f1785cf8c7554a"></p> <p data-id="53407cb1d103ecabf6f1785cf8c7554a"></p> <p data-id="0b7b29d7656d8d29ec3286a241de010e"><strong>Example 1:</strong></p> Input: [2, 1, 5, 1, 3, 2], k=3  Output: 9 Explanation: Subarray with maximum sum is [5, 1, 3]. &nbsp; &nbsp; <p data-id="0b7b29d7656d8d29ec3286a241de010e"><strong>Example 2:</strong></p> Input: [2, 3, 4, 1, 5], k=2  Output: 7 Explanation: Subarray with maximum sum is [3, 4]. <h3 id="try-it-yourself" data-id="091e53f55f3812664765f2ff8f3aff6d"></h3> &nbsp; <h3 id="solution" data-id="f69ad95ba722a9debe3d34a9dec8f95b">Solution</h3> A basic brute force solution will be to calculate the sum of all <strong>‘k’</strong> sized subarrays of the given array, to find the subarray with the highest sum. We can start from every index of the given array and add the next <strong>‘k’</strong> elements to find the sum of the subarray. Following is the visual representation of this algorithm for Example-1: &nbsp; <img class="size-full wp-image-2998" src="https://www.golibrary.co/wp-content/uploads/2020/03/subarray-sum.png" alt="subarray sum" width="843" height="492" /><br/> subarray sum depiction &nbsp; &nbsp; Javascript Code below (brute force approach):- &nbsp; &nbsp; <div class="wp-block-codemirror-blocks code-block alignwide"> <pre class="CodeMirror" data-setting="{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:true,&quot;lineWrapping&quot;:true,&quot;styleActiveLine&quot;:true,&quot;readOnly&quot;:false,&quot;align&quot;:&quot;wide&quot;}">&lt;script&gt; function max_sub_array_of_size_k(k, arr) { let maxSum = 0, windowSum = 0; // loop through start till array length - k for (i = 0; i &lt; arr.length - k + 1; i++) { windowSum = 0; // loop through i to i + k elements for (j = i; j &lt; i + k; j++) { windowSum += arr[j]; } maxSum = Math.max(maxSum, windowSum); } return maxSum; } document.write(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(3, [2, 1, 5, 1, 3, 2])}&lt;br/&gt;`); document.write(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(2, [2, 3, 4, 1, 5])}&lt;br/&gt;`); &lt;/script&gt; </pre> </div> &nbsp; &nbsp; The time complexity of the above algorithm will be <strong>O(N*K)</strong>, where <strong>‘N’</strong> is the total number of elements in the given array and K is the size of sub-array. The above solution works but isn't efficient for large data sets. It will fail and run out of time. We need a better solution. To solve such problems, we use a pattern called <strong>"sliding window pattern or mechanism"</strong> &nbsp; &nbsp; <h4 id="a-better-approach" data-id="2cdf66315d2c2a56f4edd8ce9be179bb">Sliding window mechanism</h4> &nbsp; <p data-id="581101dc38b16279e9eb58f9eaa3e0d8">If we observe closely, we realize that we can reuse the sum of previous sub-array at each point to calculate the sum of current sub-array a.k.a <strong>window</strong>. We consider each sub-array as a <strong>Sliding Window</strong> of size <strong>‘k’</strong>. To calculate the sum of the next sub-array, we need to slide the window ahead by one element. So to slide the window forward and calculate the sum of the new position of the sliding window, we need to do two things:</p> <ol data-id="27b891f85213769fc57d13aac390468a"> <li>Subtract the element going out of the sliding window i.e., subtract the first element of the window.</li> <li>Add the new element getting included in the sliding window i.e., the element coming right after the end of the window.</li> </ol> &nbsp; <p data-id="b67a035c1779640e66cb49bfb45dce88">This approach will save us from re-calculating the sum of the overlapping part of the sliding window. Here is what our algorithm will look like:</p> <div class="wp-block-codemirror-blocks code-block alignwide"> <pre class="CodeMirror" data-setting="{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:true,&quot;lineWrapping&quot;:true,&quot;styleActiveLine&quot;:true,&quot;readOnly&quot;:false,&quot;align&quot;:&quot;wide&quot;}">&lt;script&gt; function max_sub_array_of_size_k(k, arr) { var maxSum = 0; var windowStart = 0; var windowSum = 0; for (var windowEnd = 0; windowEnd &lt; arr.length; windowEnd++) { windowSum += arr[windowEnd]; if (windowEnd &gt;= k - 1) { maxSum = Math.max(maxSum, windowSum); windowSum -= arr[windowStart]; windowStart++; } } return maxSum; } document.write(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(3, [2, 1, 5, 1, 3, 2])}&lt;br/&gt;`); document.write(`Maximum sum of a subarray of size KL ${max_sub_array_of_size_k(2, [2, 3, 4, 1, 5])}&lt;br/&gt;`); &lt;/script&gt;</pre> </div> <h4 data-id="4aee6881c21420310492cbdf7cb9003b"></h4> &nbsp; <h4 id="time-complexity" data-id="4aee6881c21420310492cbdf7cb9003b">Time Complexity </h4> <p data-id="f9c90e2b944bd92ebc0b1c2fccda303e">The time complexity of the above algorithm will be O(N).</p> <h4 id="space-complexity" data-id="4557d9eda0cfe746575b79994109e4b8">Space Complexity </h4> <p data-id="31c0baa71fdd532a3e7bbd7007cac80b">The algorithm runs in constant space O(1).</p> &nbsp; &nbsp; <br /><center><hr/><em>Posted from my blog with <a href='https://wordpress.org/plugins/steempress/'>SteemPress</a> : https://www.golibrary.co/finding-maximum-size-subarray-with-sum-k-in-a-given-array/ </em><hr/></center>
json metadata{"community":"steempress","app":"steempress","image":["https://www.golibrary.co/wp-content/uploads/2020/03/subarray-sum.png"],"tags":["steempress","steem","golibrary","technology","maximum"],"canonical_url":"https://www.golibrary.co/finding-maximum-size-subarray-with-sum-k-in-a-given-array/"}
Transaction InfoBlock #41730033/Trx dabf97f21c83999ff85ff5aa4eac4d63eee9c629
View Raw JSON Data
{
  "trx_id": "dabf97f21c83999ff85ff5aa4eac4d63eee9c629",
  "block": 41730033,
  "trx_in_block": 6,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-17T11:57:15",
  "op": [
    "comment",
    {
      "parent_author": "",
      "parent_permlink": "steempress",
      "author": "golibrary",
      "permlink": "findingmaximumsizesubarraywithsumkinagivenarray-l9bvm7k1ra",
      "title": "Finding maximum size subarray with sum K in a given array",
      "body": "<center>https://www.golibrary.co/wp-content/uploads/2020/03/subarray-sum.png</center> <br/><h3 id=\"problem-statement\" data-id=\"0f3c185023ec811f417e671bc39b2ae2\">Problem Statement</h3>\r\n<p data-id=\"53407cb1d103ecabf6f1785cf8c7554a\">Given an array of positive numbers and a positive number ‘k’, find the <strong>maximum sum of any contiguous subarray of size ‘k’</strong>.</p>\r\n<p data-id=\"53407cb1d103ecabf6f1785cf8c7554a\"></p>\r\n<p data-id=\"53407cb1d103ecabf6f1785cf8c7554a\"></p>\r\n<p data-id=\"0b7b29d7656d8d29ec3286a241de010e\"><strong>Example 1:</strong></p>\r\nInput: [2, 1, 5, 1, 3, 2], k=3 \r\n\r\nOutput: 9\r\n\r\nExplanation: Subarray with maximum sum is [5, 1, 3].\r\n\r\n&nbsp;\r\n\r\n&nbsp;\r\n<p data-id=\"0b7b29d7656d8d29ec3286a241de010e\"><strong>Example 2:</strong></p>\r\nInput: [2, 3, 4, 1, 5], k=2 \r\n\r\nOutput: 7\r\n\r\nExplanation: Subarray with maximum sum is [3, 4].\r\n<h3 id=\"try-it-yourself\" data-id=\"091e53f55f3812664765f2ff8f3aff6d\"></h3>\r\n&nbsp;\r\n<h3 id=\"solution\" data-id=\"f69ad95ba722a9debe3d34a9dec8f95b\">Solution</h3>\r\nA basic brute force solution will be to calculate the sum of all <strong>‘k’</strong> sized subarrays of the given array, to find the subarray with the highest sum. We can start from every index of the given array and add the next <strong>‘k’</strong> elements to find the sum of the subarray. Following is the visual representation of this algorithm for Example-1:\r\n\r\n&nbsp;\r\n\r <img class=\"size-full wp-image-2998\" src=\"https://www.golibrary.co/wp-content/uploads/2020/03/subarray-sum.png\" alt=\"subarray sum\" width=\"843\" height=\"492\" /><br/> subarray sum depiction\r\n\r\n&nbsp;\r\n\r\n&nbsp;\r\n\r\nJavascript Code below (brute force approach):-\r\n\r\n&nbsp;\r\n\r\n&nbsp;\r\n<div class=\"wp-block-codemirror-blocks code-block alignwide\">\r\n<pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:true,&quot;lineWrapping&quot;:true,&quot;styleActiveLine&quot;:true,&quot;readOnly&quot;:false,&quot;align&quot;:&quot;wide&quot;}\">&lt;script&gt;\r\nfunction max_sub_array_of_size_k(k, arr) {\r\n  let maxSum = 0,\r\n    windowSum = 0;\r\n  // loop through start till array length - k\r\n  for (i = 0; i &lt; arr.length - k + 1; i++) {\r\n    windowSum = 0;\r\n    // loop through i to i + k elements\r\n    for (j = i; j &lt; i + k; j++) {\r\n      windowSum += arr[j];\r\n    }\r\n    maxSum = Math.max(maxSum, windowSum);\r\n  }\r\n  return maxSum;\r\n}\r\n\r\n\r\ndocument.write(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(3, [2, 1, 5, 1, 3, 2])}&lt;br/&gt;`);\r\ndocument.write(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(2, [2, 3, 4, 1, 5])}&lt;br/&gt;`);\r\n&lt;/script&gt;\r\n</pre>\r\n</div>\r\n&nbsp;\r\n\r\n&nbsp;\r\n\r\nThe time complexity of the above algorithm will be <strong>O(N*K)</strong>, where <strong>‘N’</strong> is the total number of elements in the given array and K is the size of sub-array.\r\n\r\nThe above solution works but isn't efficient for large data sets. It will fail and run out of time. We need a better solution.\r\n\r\nTo solve such problems, we use a pattern called <strong>\"sliding window pattern or mechanism\"</strong>\r\n\r\n&nbsp;\r\n\r\n&nbsp;\r\n<h4 id=\"a-better-approach\" data-id=\"2cdf66315d2c2a56f4edd8ce9be179bb\">Sliding window mechanism</h4>\r\n&nbsp;\r\n<p data-id=\"581101dc38b16279e9eb58f9eaa3e0d8\">If we observe closely, we realize that we can reuse the sum of previous sub-array at each point to calculate the sum of current sub-array a.k.a <strong>window</strong>. We consider each sub-array as a <strong>Sliding Window</strong> of size <strong>‘k’</strong>. To calculate the sum of the next sub-array, we need to slide the window ahead by one element. So to slide the window forward and calculate the sum of the new position of the sliding window, we need to do two things:</p>\r\n\r\n<ol data-id=\"27b891f85213769fc57d13aac390468a\">\r\n <li>Subtract the element going out of the sliding window i.e., subtract the first element of the window.</li>\r\n <li>Add the new element getting included in the sliding window i.e., the element coming right after the end of the window.</li>\r\n</ol>\r\n&nbsp;\r\n<p data-id=\"b67a035c1779640e66cb49bfb45dce88\">This approach will save us from re-calculating the sum of the overlapping part of the sliding window. Here is what our algorithm will look like:</p>\r\n\r\n<div class=\"wp-block-codemirror-blocks code-block alignwide\">\r\n<pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:true,&quot;lineWrapping&quot;:true,&quot;styleActiveLine&quot;:true,&quot;readOnly&quot;:false,&quot;align&quot;:&quot;wide&quot;}\">&lt;script&gt;\r\nfunction max_sub_array_of_size_k(k, arr) {\r\nvar maxSum = 0;\r\nvar windowStart = 0;\r\n\r\nvar windowSum = 0;\r\n\r\n\r\nfor (var windowEnd = 0; windowEnd &lt; arr.length; windowEnd++) {\r\nwindowSum += arr[windowEnd];\r\n\r\nif (windowEnd &gt;= k - 1) {\r\nmaxSum = Math.max(maxSum, windowSum);\r\nwindowSum -= arr[windowStart];\r\nwindowStart++;\r\n}\r\n}\r\n\r\nreturn maxSum;\r\n}\r\n\r\n\r\ndocument.write(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(3, [2, 1, 5, 1, 3, 2])}&lt;br/&gt;`);\r\ndocument.write(`Maximum sum of a subarray of size KL ${max_sub_array_of_size_k(2, [2, 3, 4, 1, 5])}&lt;br/&gt;`);\r\n&lt;/script&gt;</pre>\r\n</div>\r\n<h4 data-id=\"4aee6881c21420310492cbdf7cb9003b\"></h4>\r\n&nbsp;\r\n<h4 id=\"time-complexity\" data-id=\"4aee6881c21420310492cbdf7cb9003b\">Time Complexity </h4>\r\n<p data-id=\"f9c90e2b944bd92ebc0b1c2fccda303e\">The time complexity of the above algorithm will be O(N).</p>\r\n\r\n<h4 id=\"space-complexity\" data-id=\"4557d9eda0cfe746575b79994109e4b8\">Space Complexity </h4>\r\n<p data-id=\"31c0baa71fdd532a3e7bbd7007cac80b\">The algorithm runs in constant space O(1).</p>\r\n&nbsp;\r\n\r\n&nbsp; <br /><center><hr/><em>Posted from my blog with <a href='https://wordpress.org/plugins/steempress/'>SteemPress</a> : https://www.golibrary.co/finding-maximum-size-subarray-with-sum-k-in-a-given-array/ </em><hr/></center> ",
      "json_metadata": "{\"community\":\"steempress\",\"app\":\"steempress\",\"image\":[\"https://www.golibrary.co/wp-content/uploads/2020/03/subarray-sum.png\"],\"tags\":[\"steempress\",\"steem\",\"golibrary\",\"technology\",\"maximum\"],\"canonical_url\":\"https://www.golibrary.co/finding-maximum-size-subarray-with-sum-k-in-a-given-array/\"}"
    }
  ]
}
2020/03/17 11:57:09
voternanobot
authorgolibrary
permlinkfindingmaximumsizesubarraywithsumkinagivenarray-l9bvm7k1ra
weight5000 (50.00%)
Transaction InfoBlock #41730031/Trx 6aa945bc1e6d4455fd23dc88a8495bd0ee45e76a
View Raw JSON Data
{
  "trx_id": "6aa945bc1e6d4455fd23dc88a8495bd0ee45e76a",
  "block": 41730031,
  "trx_in_block": 17,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-17T11:57:09",
  "op": [
    "vote",
    {
      "voter": "nanobot",
      "author": "golibrary",
      "permlink": "findingmaximumsizesubarraywithsumkinagivenarray-l9bvm7k1ra",
      "weight": 5000
    }
  ]
}
2020/03/17 11:56:54
parent author
parent permlinksteempress
authorgolibrary
permlinkfindingmaximumsizesubarraywithsumkinagivenarray-l9bvm7k1ra
titleFinding maximum size subarray with sum K in a given array
body<center>https://www.golibrary.co/wp-content/uploads/2020/03/subarray-sum.png</center> <br/><h3 id="problem-statement" data-id="0f3c185023ec811f417e671bc39b2ae2">Problem Statement</h3> <p data-id="53407cb1d103ecabf6f1785cf8c7554a">Given an array of positive numbers and a positive number ‘k’, find the <strong>maximum sum of any contiguous subarray of size ‘k’</strong>.</p> <p data-id="0b7b29d7656d8d29ec3286a241de010e"><strong>Example 1:</strong></p> Input: [2, 1, 5, 1, 3, 2], k=3  Output: 9 Explanation: Subarray with maximum sum is [5, 1, 3]. &nbsp; &nbsp; <p data-id="0b7b29d7656d8d29ec3286a241de010e"><strong>Example 2:</strong></p> Input: [2, 3, 4, 1, 5], k=2  Output: 7 Explanation: Subarray with maximum sum is [3, 4]. <h3 id="try-it-yourself" data-id="091e53f55f3812664765f2ff8f3aff6d"></h3> &nbsp; <h3 id="solution" data-id="f69ad95ba722a9debe3d34a9dec8f95b">Solution</h3> A basic brute force solution will be to calculate the sum of all <strong>‘k’</strong> sized subarrays of the given array, to find the subarray with the highest sum. We can start from every index of the given array and add the next <strong>‘k’</strong> elements to find the sum of the subarray. Following is the visual representation of this algorithm for Example-1: &nbsp; <img class="size-full wp-image-2998" src="https://www.golibrary.co/wp-content/uploads/2020/03/subarray-sum.png" alt="subarray sum" width="843" height="492" /><br/> subarray sum depiction &nbsp; &nbsp; Javascript Code below (brute force approach):- &nbsp; &nbsp; <div class="wp-block-codemirror-blocks code-block alignwide"> <pre class="CodeMirror" data-setting="{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:true,&quot;lineWrapping&quot;:true,&quot;styleActiveLine&quot;:true,&quot;readOnly&quot;:false,&quot;align&quot;:&quot;wide&quot;}">&lt;script&gt; function max_sub_array_of_size_k(k, arr) { let maxSum = 0, windowSum = 0; // loop through start till array length - k for (i = 0; i &lt; arr.length - k + 1; i++) { windowSum = 0; // loop through i to i + k elements for (j = i; j &lt; i + k; j++) { windowSum += arr[j]; } maxSum = Math.max(maxSum, windowSum); } return maxSum; } document.write(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(3, [2, 1, 5, 1, 3, 2])}&lt;br/&gt;`); document.write(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(2, [2, 3, 4, 1, 5])}&lt;br/&gt;`); &lt;/script&gt; </pre> </div> &nbsp; &nbsp; The time complexity of the above algorithm will be <strong>O(N*K)</strong>, where <strong>‘N’</strong> is the total number of elements in the given array and K is the size of sub-array. The above solution works but isn't efficient for large data sets. It will fail and run out of time. We need a better solution. To solve such problems, we use a pattern called <strong>"sliding window pattern or mechanism"</strong> &nbsp; &nbsp; <h4 id="a-better-approach" data-id="2cdf66315d2c2a56f4edd8ce9be179bb">Sliding window mechanism</h4> &nbsp; <p data-id="581101dc38b16279e9eb58f9eaa3e0d8">If we observe closely, we realize that we can reuse the sum of previous sub-array at each point to calculate the sum of current sub-array a.k.a <strong>window</strong>. We consider each sub-array as a <strong>Sliding Window</strong> of size <strong>‘k’</strong>. To calculate the sum of the next sub-array, we need to slide the window ahead by one element. So to slide the window forward and calculate the sum of the new position of the sliding window, we need to do two things:</p> <ol data-id="27b891f85213769fc57d13aac390468a"> <li>Subtract the element going out of the sliding window i.e., subtract the first element of the window.</li> <li>Add the new element getting included in the sliding window i.e., the element coming right after the end of the window.</li> </ol> &nbsp; <p data-id="b67a035c1779640e66cb49bfb45dce88">This approach will save us from re-calculating the sum of the overlapping part of the sliding window. Here is what our algorithm will look like:</p> <p data-id="b67a035c1779640e66cb49bfb45dce88"></p> <p data-id="b67a035c1779640e66cb49bfb45dce88"></p> <p data-id="b67a035c1779640e66cb49bfb45dce88"> </p> <div class="wp-block-codemirror-blocks code-block alignwide"> <pre class="CodeMirror" data-setting="{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:true,&quot;lineWrapping&quot;:true,&quot;styleActiveLine&quot;:true,&quot;readOnly&quot;:false,&quot;align&quot;:&quot;wide&quot;}">&lt;script&gt; function max_sub_array_of_size_k(k, arr) { var maxSum = 0; var windowStart = 0; var windowSum = 0; for (var windowEnd = 0; windowEnd &lt; arr.length; windowEnd++) { windowSum += arr[windowEnd]; if (windowEnd &gt;= k - 1) { maxSum = Math.max(maxSum, windowSum); windowSum -= arr[windowStart]; windowStart++; } } return maxSum; } document.write(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(3, [2, 1, 5, 1, 3, 2])}&lt;br/&gt;`); document.write(`Maximum sum of a subarray of size KL ${max_sub_array_of_size_k(2, [2, 3, 4, 1, 5])}&lt;br/&gt;`); &lt;/script&gt;</pre> </div> <h4 data-id="4aee6881c21420310492cbdf7cb9003b"></h4> &nbsp; <h4 id="time-complexity" data-id="4aee6881c21420310492cbdf7cb9003b">Time Complexity </h4> <p data-id="f9c90e2b944bd92ebc0b1c2fccda303e">The time complexity of the above algorithm will be O(N).</p> <p data-id="f9c90e2b944bd92ebc0b1c2fccda303e"></p> <p data-id="f9c90e2b944bd92ebc0b1c2fccda303e"></p> <p data-id="f9c90e2b944bd92ebc0b1c2fccda303e"> </p> <h4 id="space-complexity" data-id="4557d9eda0cfe746575b79994109e4b8">Space Complexity </h4> <p data-id="31c0baa71fdd532a3e7bbd7007cac80b">The algorithm runs in constant space O(1).</p> &nbsp; &nbsp; <br /><center><hr/><em>Posted from my blog with <a href='https://wordpress.org/plugins/steempress/'>SteemPress</a> : https://www.golibrary.co/finding-maximum-size-subarray-with-sum-k-in-a-given-array/ </em><hr/></center>
json metadata{"community":"steempress","app":"steempress","image":["https://www.golibrary.co/wp-content/uploads/2020/03/subarray-sum.png"],"tags":["steempress","steem","golibrary","technology","maximum"],"canonical_url":"https://www.golibrary.co/finding-maximum-size-subarray-with-sum-k-in-a-given-array/"}
Transaction InfoBlock #41730026/Trx 4b4c2523420eb0a4cf437b52dc4bd8c8c71dea47
View Raw JSON Data
{
  "trx_id": "4b4c2523420eb0a4cf437b52dc4bd8c8c71dea47",
  "block": 41730026,
  "trx_in_block": 18,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-17T11:56:54",
  "op": [
    "comment",
    {
      "parent_author": "",
      "parent_permlink": "steempress",
      "author": "golibrary",
      "permlink": "findingmaximumsizesubarraywithsumkinagivenarray-l9bvm7k1ra",
      "title": "Finding maximum size subarray with sum K in a given array",
      "body": "<center>https://www.golibrary.co/wp-content/uploads/2020/03/subarray-sum.png</center> <br/><h3 id=\"problem-statement\" data-id=\"0f3c185023ec811f417e671bc39b2ae2\">Problem Statement</h3>\r\n<p data-id=\"53407cb1d103ecabf6f1785cf8c7554a\">Given an array of positive numbers and a positive number ‘k’, find the <strong>maximum sum of any contiguous subarray of size ‘k’</strong>.</p>\r\n<p data-id=\"0b7b29d7656d8d29ec3286a241de010e\"><strong>Example 1:</strong></p>\r\nInput: [2, 1, 5, 1, 3, 2], k=3 \r\n\r\nOutput: 9\r\n\r\nExplanation: Subarray with maximum sum is [5, 1, 3].\r\n\r\n&nbsp;\r\n\r\n&nbsp;\r\n<p data-id=\"0b7b29d7656d8d29ec3286a241de010e\"><strong>Example 2:</strong></p>\r\nInput: [2, 3, 4, 1, 5], k=2 \r\n\r\nOutput: 7\r\n\r\nExplanation: Subarray with maximum sum is [3, 4].\r\n<h3 id=\"try-it-yourself\" data-id=\"091e53f55f3812664765f2ff8f3aff6d\"></h3>\r\n&nbsp;\r\n<h3 id=\"solution\" data-id=\"f69ad95ba722a9debe3d34a9dec8f95b\">Solution</h3>\r\nA basic brute force solution will be to calculate the sum of all <strong>‘k’</strong> sized subarrays of the given array, to find the subarray with the highest sum. We can start from every index of the given array and add the next <strong>‘k’</strong> elements to find the sum of the subarray. Following is the visual representation of this algorithm for Example-1:\r\n\r\n&nbsp;\r\n\r <img class=\"size-full wp-image-2998\" src=\"https://www.golibrary.co/wp-content/uploads/2020/03/subarray-sum.png\" alt=\"subarray sum\" width=\"843\" height=\"492\" /><br/> subarray sum depiction\r\n\r\n&nbsp;\r\n\r\n&nbsp;\r\n\r\nJavascript Code below (brute force approach):-\r\n\r\n&nbsp;\r\n\r\n&nbsp;\r\n<div class=\"wp-block-codemirror-blocks code-block alignwide\">\r\n<pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:true,&quot;lineWrapping&quot;:true,&quot;styleActiveLine&quot;:true,&quot;readOnly&quot;:false,&quot;align&quot;:&quot;wide&quot;}\">&lt;script&gt;\r\nfunction max_sub_array_of_size_k(k, arr) {\r\n  let maxSum = 0,\r\n    windowSum = 0;\r\n  // loop through start till array length - k\r\n  for (i = 0; i &lt; arr.length - k + 1; i++) {\r\n    windowSum = 0;\r\n    // loop through i to i + k elements\r\n    for (j = i; j &lt; i + k; j++) {\r\n      windowSum += arr[j];\r\n    }\r\n    maxSum = Math.max(maxSum, windowSum);\r\n  }\r\n  return maxSum;\r\n}\r\n\r\n\r\ndocument.write(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(3, [2, 1, 5, 1, 3, 2])}&lt;br/&gt;`);\r\ndocument.write(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(2, [2, 3, 4, 1, 5])}&lt;br/&gt;`);\r\n&lt;/script&gt;\r\n</pre>\r\n</div>\r\n&nbsp;\r\n\r\n&nbsp;\r\n\r\nThe time complexity of the above algorithm will be <strong>O(N*K)</strong>, where <strong>‘N’</strong> is the total number of elements in the given array and K is the size of sub-array.\r\n\r\nThe above solution works but isn't efficient for large data sets. It will fail and run out of time. We need a better solution.\r\n\r\nTo solve such problems, we use a pattern called <strong>\"sliding window pattern or mechanism\"</strong>\r\n\r\n&nbsp;\r\n\r\n&nbsp;\r\n<h4 id=\"a-better-approach\" data-id=\"2cdf66315d2c2a56f4edd8ce9be179bb\">Sliding window mechanism</h4>\r\n&nbsp;\r\n<p data-id=\"581101dc38b16279e9eb58f9eaa3e0d8\">If we observe closely, we realize that we can reuse the sum of previous sub-array at each point to calculate the sum of current sub-array a.k.a <strong>window</strong>. We consider each sub-array as a <strong>Sliding Window</strong> of size <strong>‘k’</strong>. To calculate the sum of the next sub-array, we need to slide the window ahead by one element. So to slide the window forward and calculate the sum of the new position of the sliding window, we need to do two things:</p>\r\n\r\n<ol data-id=\"27b891f85213769fc57d13aac390468a\">\r\n <li>Subtract the element going out of the sliding window i.e., subtract the first element of the window.</li>\r\n <li>Add the new element getting included in the sliding window i.e., the element coming right after the end of the window.</li>\r\n</ol>\r\n&nbsp;\r\n<p data-id=\"b67a035c1779640e66cb49bfb45dce88\">This approach will save us from re-calculating the sum of the overlapping part of the sliding window. Here is what our algorithm will look like:</p>\r\n<p data-id=\"b67a035c1779640e66cb49bfb45dce88\"></p>\r\n<p data-id=\"b67a035c1779640e66cb49bfb45dce88\"></p>\r\n<p data-id=\"b67a035c1779640e66cb49bfb45dce88\">\r\n\r\n\r\n</p>\r\n\r\n<div class=\"wp-block-codemirror-blocks code-block alignwide\">\r\n<pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:true,&quot;lineWrapping&quot;:true,&quot;styleActiveLine&quot;:true,&quot;readOnly&quot;:false,&quot;align&quot;:&quot;wide&quot;}\">&lt;script&gt;\r\nfunction max_sub_array_of_size_k(k, arr) {\r\nvar maxSum = 0;\r\nvar windowStart = 0;\r\n\r\nvar windowSum = 0;\r\n\r\n\r\nfor (var windowEnd = 0; windowEnd &lt; arr.length; windowEnd++) {\r\nwindowSum += arr[windowEnd];\r\n\r\nif (windowEnd &gt;= k - 1) {\r\nmaxSum = Math.max(maxSum, windowSum);\r\nwindowSum -= arr[windowStart];\r\nwindowStart++;\r\n}\r\n}\r\n\r\nreturn maxSum;\r\n}\r\n\r\n\r\ndocument.write(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(3, [2, 1, 5, 1, 3, 2])}&lt;br/&gt;`);\r\ndocument.write(`Maximum sum of a subarray of size KL ${max_sub_array_of_size_k(2, [2, 3, 4, 1, 5])}&lt;br/&gt;`);\r\n&lt;/script&gt;</pre>\r\n</div>\r\n<h4 data-id=\"4aee6881c21420310492cbdf7cb9003b\"></h4>\r\n&nbsp;\r\n<h4 id=\"time-complexity\" data-id=\"4aee6881c21420310492cbdf7cb9003b\">Time Complexity </h4>\r\n<p data-id=\"f9c90e2b944bd92ebc0b1c2fccda303e\">The time complexity of the above algorithm will be O(N).</p>\r\n<p data-id=\"f9c90e2b944bd92ebc0b1c2fccda303e\"></p>\r\n<p data-id=\"f9c90e2b944bd92ebc0b1c2fccda303e\"></p>\r\n<p data-id=\"f9c90e2b944bd92ebc0b1c2fccda303e\">\r\n\r\n</p>\r\n\r\n<h4 id=\"space-complexity\" data-id=\"4557d9eda0cfe746575b79994109e4b8\">Space Complexity </h4>\r\n<p data-id=\"31c0baa71fdd532a3e7bbd7007cac80b\">The algorithm runs in constant space O(1).</p>\r\n&nbsp;\r\n\r\n&nbsp; <br /><center><hr/><em>Posted from my blog with <a href='https://wordpress.org/plugins/steempress/'>SteemPress</a> : https://www.golibrary.co/finding-maximum-size-subarray-with-sum-k-in-a-given-array/ </em><hr/></center> ",
      "json_metadata": "{\"community\":\"steempress\",\"app\":\"steempress\",\"image\":[\"https://www.golibrary.co/wp-content/uploads/2020/03/subarray-sum.png\"],\"tags\":[\"steempress\",\"steem\",\"golibrary\",\"technology\",\"maximum\"],\"canonical_url\":\"https://www.golibrary.co/finding-maximum-size-subarray-with-sum-k-in-a-given-array/\"}"
    }
  ]
}
2020/03/17 11:55:18
parent author
parent permlinksteempress
authorgolibrary
permlinkfindingmaximumsizesubarraywithsumkinagivenarray-l9bvm7k1ra
titleFinding maximum size subarray with sum K in a given array
body<center>https://www.golibrary.co/wp-content/uploads/2020/03/subarray-sum.png</center> <br/><h3 id="problem-statement" data-id="0f3c185023ec811f417e671bc39b2ae2">Problem Statement</h3> <p data-id="53407cb1d103ecabf6f1785cf8c7554a">Given an array of positive numbers and a positive number ‘k’, find the <strong>maximum sum of any contiguous subarray of size ‘k’</strong>.</p> <p data-id="0b7b29d7656d8d29ec3286a241de010e"><strong>Example 1:</strong></p> Input: [2, 1, 5, 1, 3, 2], k=3  Output: 9 Explanation: Subarray with maximum sum is [5, 1, 3]. &nbsp; &nbsp; <p data-id="0b7b29d7656d8d29ec3286a241de010e"><strong>Example 2:</strong></p> Input: [2, 3, 4, 1, 5], k=2  Output: 7 Explanation: Subarray with maximum sum is [3, 4]. <h3 id="try-it-yourself" data-id="091e53f55f3812664765f2ff8f3aff6d"></h3> &nbsp; <h3 id="solution" data-id="f69ad95ba722a9debe3d34a9dec8f95b">Solution</h3> A basic brute force solution will be to calculate the sum of all <strong>‘k’</strong> sized subarrays of the given array, to find the subarray with the highest sum. We can start from every index of the given array and add the next <strong>‘k’</strong> elements to find the sum of the subarray. Following is the visual representation of this algorithm for Example-1: &nbsp; <img class="size-full wp-image-2998" src="https://www.golibrary.co/wp-content/uploads/2020/03/subarray-sum.png" alt="subarray sum" width="843" height="492" /><br/> subarray sum depiction &nbsp; &nbsp; Javascript Code below (brute force approach):- &nbsp; &nbsp; <div class="wp-block-codemirror-blocks code-block alignwide"> <pre class="CodeMirror" data-setting="{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:true,&quot;lineWrapping&quot;:true,&quot;styleActiveLine&quot;:true,&quot;readOnly&quot;:false,&quot;align&quot;:&quot;wide&quot;}">&lt;script&gt; function max_sub_array_of_size_k(k, arr) { let maxSum = 0, windowSum = 0; // loop through start till array length - k for (i = 0; i &lt; arr.length - k + 1; i++) { windowSum = 0; // loop through i to i + k elements for (j = i; j &lt; i + k; j++) { windowSum += arr[j]; } maxSum = Math.max(maxSum, windowSum); } return maxSum; } document.write(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(3, [2, 1, 5, 1, 3, 2])}&lt;br/&gt;`); document.write(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(2, [2, 3, 4, 1, 5])}&lt;br/&gt;`); &lt;/script&gt; </pre> </div> &nbsp; &nbsp; The time complexity of the above algorithm will be <strong>O(N*K)</strong>, where <strong>‘N’</strong> is the total number of elements in the given array and K is the size of sub-array. The above solution works but isn't efficient for large data sets. It will fail and run out of time. We need a better solution. To solve such problems, we use a pattern called <strong>"sliding window pattern or mechanism"</strong> &nbsp; &nbsp; <h4 id="a-better-approach" data-id="2cdf66315d2c2a56f4edd8ce9be179bb">Sliding window mechanism</h4> &nbsp; <p data-id="581101dc38b16279e9eb58f9eaa3e0d8">If we observe closely, we realize that we can reuse the sum of previous sub-array at each point to calculate the sum of current sub-array a.k.a <strong>window</strong>. We consider each sub-array as a <strong>Sliding Window</strong> of size <strong>‘k’</strong>. To calculate the sum of the next sub-array, we need to slide the window ahead by one element. So to slide the window forward and calculate the sum of the new position of the sliding window, we need to do two things:</p> <ol data-id="27b891f85213769fc57d13aac390468a"> <li>Subtract the element going out of the sliding window i.e., subtract the first element of the window.</li> <li>Add the new element getting included in the sliding window i.e., the element coming right after the end of the window.</li> </ol> &nbsp; <p data-id="b67a035c1779640e66cb49bfb45dce88">This approach will save us from re-calculating the sum of the overlapping part of the sliding window. Here is what our algorithm will look like:</p> <p data-id="b67a035c1779640e66cb49bfb45dce88"></p> <div class="wp-block-codemirror-blocks code-block alignwide"> <pre class="CodeMirror" data-setting="{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:true,&quot;lineWrapping&quot;:true,&quot;styleActiveLine&quot;:true,&quot;readOnly&quot;:false,&quot;align&quot;:&quot;wide&quot;}">&lt;script&gt; function max_sub_array_of_size_k(k, arr) { var maxSum = 0; var windowStart = 0; var windowSum = 0; for (var windowEnd = 0; windowEnd &lt; arr.length; windowEnd++) { windowSum += arr[windowEnd]; if (windowEnd &gt;= k - 1) { maxSum = Math.max(maxSum, windowSum); windowSum -= arr[windowStart]; windowStart++; } } return maxSum; } document.write(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(3, [2, 1, 5, 1, 3, 2])}&lt;br/&gt;`); document.write(`Maximum sum of a subarray of size KL ${max_sub_array_of_size_k(2, [2, 3, 4, 1, 5])}&lt;br/&gt;`); &lt;/script&gt;</pre> </div> <h4 data-id="4aee6881c21420310492cbdf7cb9003b"></h4> &nbsp; <h4 id="time-complexity" data-id="4aee6881c21420310492cbdf7cb9003b">Time Complexity </h4> <p data-id="f9c90e2b944bd92ebc0b1c2fccda303e">The time complexity of the above algorithm will be O(N).</p> <p data-id="f9c90e2b944bd92ebc0b1c2fccda303e"></p> <h4 id="space-complexity" data-id="4557d9eda0cfe746575b79994109e4b8">Space Complexity </h4> <p data-id="31c0baa71fdd532a3e7bbd7007cac80b">The algorithm runs in constant space O(1).</p> &nbsp; &nbsp; <br /><center><hr/><em>Posted from my blog with <a href='https://wordpress.org/plugins/steempress/'>SteemPress</a> : https://www.golibrary.co/finding-maximum-size-subarray-with-sum-k-in-a-given-array/ </em><hr/></center>
json metadata{"community":"steempress","app":"steempress","image":["https://www.golibrary.co/wp-content/uploads/2020/03/subarray-sum.png"],"tags":["steempress","steem","golibrary","technology","maximum"],"canonical_url":"https://www.golibrary.co/finding-maximum-size-subarray-with-sum-k-in-a-given-array/"}
Transaction InfoBlock #41729994/Trx a5d7610481e9774ea1a94452d9548b41c08fb10e
View Raw JSON Data
{
  "trx_id": "a5d7610481e9774ea1a94452d9548b41c08fb10e",
  "block": 41729994,
  "trx_in_block": 8,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-17T11:55:18",
  "op": [
    "comment",
    {
      "parent_author": "",
      "parent_permlink": "steempress",
      "author": "golibrary",
      "permlink": "findingmaximumsizesubarraywithsumkinagivenarray-l9bvm7k1ra",
      "title": "Finding maximum size subarray with sum K in a given array",
      "body": "<center>https://www.golibrary.co/wp-content/uploads/2020/03/subarray-sum.png</center> <br/><h3 id=\"problem-statement\" data-id=\"0f3c185023ec811f417e671bc39b2ae2\">Problem Statement</h3>\r\n<p data-id=\"53407cb1d103ecabf6f1785cf8c7554a\">Given an array of positive numbers and a positive number ‘k’, find the <strong>maximum sum of any contiguous subarray of size ‘k’</strong>.</p>\r\n<p data-id=\"0b7b29d7656d8d29ec3286a241de010e\"><strong>Example 1:</strong></p>\r\nInput: [2, 1, 5, 1, 3, 2], k=3 \r\n\r\nOutput: 9\r\n\r\nExplanation: Subarray with maximum sum is [5, 1, 3].\r\n\r\n&nbsp;\r\n\r\n&nbsp;\r\n<p data-id=\"0b7b29d7656d8d29ec3286a241de010e\"><strong>Example 2:</strong></p>\r\nInput: [2, 3, 4, 1, 5], k=2 \r\n\r\nOutput: 7\r\n\r\nExplanation: Subarray with maximum sum is [3, 4].\r\n<h3 id=\"try-it-yourself\" data-id=\"091e53f55f3812664765f2ff8f3aff6d\"></h3>\r\n&nbsp;\r\n<h3 id=\"solution\" data-id=\"f69ad95ba722a9debe3d34a9dec8f95b\">Solution</h3>\r\nA basic brute force solution will be to calculate the sum of all <strong>‘k’</strong> sized subarrays of the given array, to find the subarray with the highest sum. We can start from every index of the given array and add the next <strong>‘k’</strong> elements to find the sum of the subarray. Following is the visual representation of this algorithm for Example-1:\r\n\r\n&nbsp;\r\n\r <img class=\"size-full wp-image-2998\" src=\"https://www.golibrary.co/wp-content/uploads/2020/03/subarray-sum.png\" alt=\"subarray sum\" width=\"843\" height=\"492\" /><br/> subarray sum depiction\r\n\r\n&nbsp;\r\n\r\n&nbsp;\r\n\r\nJavascript Code below (brute force approach):-\r\n\r\n&nbsp;\r\n\r\n&nbsp;\r\n<div class=\"wp-block-codemirror-blocks code-block alignwide\">\r\n<pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:true,&quot;lineWrapping&quot;:true,&quot;styleActiveLine&quot;:true,&quot;readOnly&quot;:false,&quot;align&quot;:&quot;wide&quot;}\">&lt;script&gt;\r\nfunction max_sub_array_of_size_k(k, arr) {\r\n  let maxSum = 0,\r\n    windowSum = 0;\r\n  // loop through start till array length - k\r\n  for (i = 0; i &lt; arr.length - k + 1; i++) {\r\n    windowSum = 0;\r\n    // loop through i to i + k elements\r\n    for (j = i; j &lt; i + k; j++) {\r\n      windowSum += arr[j];\r\n    }\r\n    maxSum = Math.max(maxSum, windowSum);\r\n  }\r\n  return maxSum;\r\n}\r\n\r\n\r\ndocument.write(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(3, [2, 1, 5, 1, 3, 2])}&lt;br/&gt;`);\r\ndocument.write(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(2, [2, 3, 4, 1, 5])}&lt;br/&gt;`);\r\n&lt;/script&gt;\r\n</pre>\r\n</div>\r\n&nbsp;\r\n\r\n&nbsp;\r\n\r\nThe time complexity of the above algorithm will be <strong>O(N*K)</strong>, where <strong>‘N’</strong> is the total number of elements in the given array and K is the size of sub-array.\r\n\r\nThe above solution works but isn't efficient for large data sets. It will fail and run out of time. We need a better solution.\r\n\r\nTo solve such problems, we use a pattern called <strong>\"sliding window pattern or mechanism\"</strong>\r\n\r\n&nbsp;\r\n\r\n&nbsp;\r\n<h4 id=\"a-better-approach\" data-id=\"2cdf66315d2c2a56f4edd8ce9be179bb\">Sliding window mechanism</h4>\r\n&nbsp;\r\n<p data-id=\"581101dc38b16279e9eb58f9eaa3e0d8\">If we observe closely, we realize that we can reuse the sum of previous sub-array at each point to calculate the sum of current sub-array a.k.a <strong>window</strong>. We consider each sub-array as a <strong>Sliding Window</strong> of size <strong>‘k’</strong>. To calculate the sum of the next sub-array, we need to slide the window ahead by one element. So to slide the window forward and calculate the sum of the new position of the sliding window, we need to do two things:</p>\r\n\r\n<ol data-id=\"27b891f85213769fc57d13aac390468a\">\r\n <li>Subtract the element going out of the sliding window i.e., subtract the first element of the window.</li>\r\n <li>Add the new element getting included in the sliding window i.e., the element coming right after the end of the window.</li>\r\n</ol>\r\n&nbsp;\r\n<p data-id=\"b67a035c1779640e66cb49bfb45dce88\">This approach will save us from re-calculating the sum of the overlapping part of the sliding window. Here is what our algorithm will look like:</p>\r\n<p data-id=\"b67a035c1779640e66cb49bfb45dce88\"></p>\r\n\r\n<div class=\"wp-block-codemirror-blocks code-block alignwide\">\r\n<pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:true,&quot;lineWrapping&quot;:true,&quot;styleActiveLine&quot;:true,&quot;readOnly&quot;:false,&quot;align&quot;:&quot;wide&quot;}\">&lt;script&gt;\r\nfunction max_sub_array_of_size_k(k, arr) {\r\nvar maxSum = 0;\r\nvar windowStart = 0;\r\n\r\nvar windowSum = 0;\r\n\r\n\r\nfor (var windowEnd = 0; windowEnd &lt; arr.length; windowEnd++) {\r\nwindowSum += arr[windowEnd];\r\n\r\nif (windowEnd &gt;= k - 1) {\r\nmaxSum = Math.max(maxSum, windowSum);\r\nwindowSum -= arr[windowStart];\r\nwindowStart++;\r\n}\r\n}\r\n\r\nreturn maxSum;\r\n}\r\n\r\n\r\ndocument.write(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(3, [2, 1, 5, 1, 3, 2])}&lt;br/&gt;`);\r\ndocument.write(`Maximum sum of a subarray of size KL ${max_sub_array_of_size_k(2, [2, 3, 4, 1, 5])}&lt;br/&gt;`);\r\n&lt;/script&gt;</pre>\r\n</div>\r\n<h4 data-id=\"4aee6881c21420310492cbdf7cb9003b\"></h4>\r\n&nbsp;\r\n<h4 id=\"time-complexity\" data-id=\"4aee6881c21420310492cbdf7cb9003b\">Time Complexity </h4>\r\n<p data-id=\"f9c90e2b944bd92ebc0b1c2fccda303e\">The time complexity of the above algorithm will be O(N).</p>\r\n<p data-id=\"f9c90e2b944bd92ebc0b1c2fccda303e\"></p>\r\n\r\n<h4 id=\"space-complexity\" data-id=\"4557d9eda0cfe746575b79994109e4b8\">Space Complexity </h4>\r\n<p data-id=\"31c0baa71fdd532a3e7bbd7007cac80b\">The algorithm runs in constant space O(1).</p>\r\n&nbsp;\r\n\r\n&nbsp; <br /><center><hr/><em>Posted from my blog with <a href='https://wordpress.org/plugins/steempress/'>SteemPress</a> : https://www.golibrary.co/finding-maximum-size-subarray-with-sum-k-in-a-given-array/ </em><hr/></center> ",
      "json_metadata": "{\"community\":\"steempress\",\"app\":\"steempress\",\"image\":[\"https://www.golibrary.co/wp-content/uploads/2020/03/subarray-sum.png\"],\"tags\":[\"steempress\",\"steem\",\"golibrary\",\"technology\",\"maximum\"],\"canonical_url\":\"https://www.golibrary.co/finding-maximum-size-subarray-with-sum-k-in-a-given-array/\"}"
    }
  ]
}
2020/03/17 11:54:42
parent author
parent permlinksteempress
authorgolibrary
permlinkfindingmaximumsizesubarraywithsumkinagivenarray-l9bvm7k1ra
titleFinding maximum size subarray with sum K in a given array
body<center>https://www.golibrary.co/wp-content/uploads/2020/03/subarray-sum.png</center> <br/><h3 id="problem-statement" data-id="0f3c185023ec811f417e671bc39b2ae2">Problem Statement</h3> <p data-id="53407cb1d103ecabf6f1785cf8c7554a">Given an array of positive numbers and a positive number ‘k’, find the <strong>maximum sum of any contiguous subarray of size ‘k’</strong>.</p> <p data-id="53407cb1d103ecabf6f1785cf8c7554a"></p> <p data-id="0b7b29d7656d8d29ec3286a241de010e"><strong>Example 1:</strong></p> Input: [2, 1, 5, 1, 3, 2], k=3  Output: 9 Explanation: Subarray with maximum sum is [5, 1, 3]. &nbsp; &nbsp; <p data-id="0b7b29d7656d8d29ec3286a241de010e"><strong>Example 2:</strong></p> Input: [2, 3, 4, 1, 5], k=2  Output: 7 Explanation: Subarray with maximum sum is [3, 4]. <h3 id="try-it-yourself" data-id="091e53f55f3812664765f2ff8f3aff6d"></h3> &nbsp; <h3 id="solution" data-id="f69ad95ba722a9debe3d34a9dec8f95b">Solution</h3> A basic brute force solution will be to calculate the sum of all <strong>‘k’</strong> sized subarrays of the given array, to find the subarray with the highest sum. We can start from every index of the given array and add the next <strong>‘k’</strong> elements to find the sum of the subarray. Following is the visual representation of this algorithm for Example-1: &nbsp; <img class="size-full wp-image-2998" src="https://www.golibrary.co/wp-content/uploads/2020/03/subarray-sum.png" alt="subarray sum" width="843" height="492" /><br/> subarray sum depiction &nbsp; &nbsp; Javascript Code below (brute force approach):- &nbsp; &nbsp; <div class="wp-block-codemirror-blocks code-block alignwide"> <pre class="CodeMirror" data-setting="{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:true,&quot;lineWrapping&quot;:true,&quot;styleActiveLine&quot;:true,&quot;readOnly&quot;:false,&quot;align&quot;:&quot;wide&quot;}">&lt;script&gt; function max_sub_array_of_size_k(k, arr) { let maxSum = 0, windowSum = 0; // loop through start till array length - k for (i = 0; i &lt; arr.length - k + 1; i++) { windowSum = 0; // loop through i to i + k elements for (j = i; j &lt; i + k; j++) { windowSum += arr[j]; } maxSum = Math.max(maxSum, windowSum); } return maxSum; } document.write(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(3, [2, 1, 5, 1, 3, 2])}&lt;br/&gt;`); document.write(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(2, [2, 3, 4, 1, 5])}&lt;br/&gt;`); &lt;/script&gt; </pre> </div> &nbsp; &nbsp; The time complexity of the above algorithm will be <strong>O(N*K)</strong>, where <strong>‘N’</strong> is the total number of elements in the given array and K is the size of sub-array. The above solution works but isn't efficient for large data sets. It will fail and run out of time. We need a better solution. To solve such problems, we use a pattern called <strong>"sliding window pattern or mechanism"</strong> &nbsp; &nbsp; <h4 id="a-better-approach" data-id="2cdf66315d2c2a56f4edd8ce9be179bb">Sliding window mechanism</h4> &nbsp; <p data-id="581101dc38b16279e9eb58f9eaa3e0d8">If we observe closely, we realize that we can reuse the sum of previous sub-array at each point to calculate the sum of current sub-array a.k.a <strong>window</strong>. We consider each sub-array as a <strong>Sliding Window</strong> of size <strong>‘k’</strong>. To calculate the sum of the next sub-array, we need to slide the window ahead by one element. So to slide the window forward and calculate the sum of the new position of the sliding window, we need to do two things:</p> <ol data-id="27b891f85213769fc57d13aac390468a"> <li>Subtract the element going out of the sliding window i.e., subtract the first element of the window.</li> <li>Add the new element getting included in the sliding window i.e., the element coming right after the end of the window.</li> </ol> &nbsp; <p data-id="b67a035c1779640e66cb49bfb45dce88">This approach will save us from re-calculating the sum of the overlapping part of the sliding window. Here is what our algorithm will look like:</p> <div class="wp-block-codemirror-blocks code-block alignwide"> <pre class="CodeMirror" data-setting="{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:true,&quot;lineWrapping&quot;:true,&quot;styleActiveLine&quot;:true,&quot;readOnly&quot;:false,&quot;align&quot;:&quot;wide&quot;}">&lt;script&gt; function max_sub_array_of_size_k(k, arr) { var maxSum = 0; var windowStart = 0; var windowSum = 0; for (var windowEnd = 0; windowEnd &lt; arr.length; windowEnd++) { windowSum += arr[windowEnd]; if (windowEnd &gt;= k - 1) { maxSum = Math.max(maxSum, windowSum); windowSum -= arr[windowStart]; windowStart++; } } return maxSum; } document.write(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(3, [2, 1, 5, 1, 3, 2])}&lt;br/&gt;`); document.write(`Maximum sum of a subarray of size KL ${max_sub_array_of_size_k(2, [2, 3, 4, 1, 5])}&lt;br/&gt;`); &lt;/script&gt;</pre> </div> <h4 data-id="4aee6881c21420310492cbdf7cb9003b"></h4> &nbsp; <h4 id="time-complexity" data-id="4aee6881c21420310492cbdf7cb9003b">Time Complexity </h4> <p data-id="f9c90e2b944bd92ebc0b1c2fccda303e">The time complexity of the above algorithm will be O(N).</p> <p data-id="f9c90e2b944bd92ebc0b1c2fccda303e"></p> <p data-id="f9c90e2b944bd92ebc0b1c2fccda303e"></p> <h4 id="space-complexity" data-id="4557d9eda0cfe746575b79994109e4b8">Space Complexity </h4> <p data-id="31c0baa71fdd532a3e7bbd7007cac80b">The algorithm runs in constant space O(1).</p> &nbsp; &nbsp; <br /><center><hr/><em>Posted from my blog with <a href='https://wordpress.org/plugins/steempress/'>SteemPress</a> : https://www.golibrary.co/finding-maximum-size-subarray-with-sum-k-in-a-given-array/ </em><hr/></center>
json metadata{"community":"steempress","app":"steempress","image":["https://www.golibrary.co/wp-content/uploads/2020/03/subarray-sum.png"],"tags":["steempress","steem","golibrary","technology","maximum"],"canonical_url":"https://www.golibrary.co/finding-maximum-size-subarray-with-sum-k-in-a-given-array/"}
Transaction InfoBlock #41729982/Trx 60f5a52a6aacd1a0707a75c2515d545307071be5
View Raw JSON Data
{
  "trx_id": "60f5a52a6aacd1a0707a75c2515d545307071be5",
  "block": 41729982,
  "trx_in_block": 6,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-17T11:54:42",
  "op": [
    "comment",
    {
      "parent_author": "",
      "parent_permlink": "steempress",
      "author": "golibrary",
      "permlink": "findingmaximumsizesubarraywithsumkinagivenarray-l9bvm7k1ra",
      "title": "Finding maximum size subarray with sum K in a given array",
      "body": "<center>https://www.golibrary.co/wp-content/uploads/2020/03/subarray-sum.png</center> <br/><h3 id=\"problem-statement\" data-id=\"0f3c185023ec811f417e671bc39b2ae2\">Problem Statement</h3>\r\n<p data-id=\"53407cb1d103ecabf6f1785cf8c7554a\">Given an array of positive numbers and a positive number ‘k’, find the <strong>maximum sum of any contiguous subarray of size ‘k’</strong>.</p>\r\n<p data-id=\"53407cb1d103ecabf6f1785cf8c7554a\"></p>\r\n<p data-id=\"0b7b29d7656d8d29ec3286a241de010e\"><strong>Example 1:</strong></p>\r\nInput: [2, 1, 5, 1, 3, 2], k=3 \r\n\r\nOutput: 9\r\n\r\nExplanation: Subarray with maximum sum is [5, 1, 3].\r\n\r\n&nbsp;\r\n\r\n&nbsp;\r\n<p data-id=\"0b7b29d7656d8d29ec3286a241de010e\"><strong>Example 2:</strong></p>\r\nInput: [2, 3, 4, 1, 5], k=2 \r\n\r\nOutput: 7\r\n\r\nExplanation: Subarray with maximum sum is [3, 4].\r\n<h3 id=\"try-it-yourself\" data-id=\"091e53f55f3812664765f2ff8f3aff6d\"></h3>\r\n&nbsp;\r\n<h3 id=\"solution\" data-id=\"f69ad95ba722a9debe3d34a9dec8f95b\">Solution</h3>\r\nA basic brute force solution will be to calculate the sum of all <strong>‘k’</strong> sized subarrays of the given array, to find the subarray with the highest sum. We can start from every index of the given array and add the next <strong>‘k’</strong> elements to find the sum of the subarray. Following is the visual representation of this algorithm for Example-1:\r\n\r\n&nbsp;\r\n\r <img class=\"size-full wp-image-2998\" src=\"https://www.golibrary.co/wp-content/uploads/2020/03/subarray-sum.png\" alt=\"subarray sum\" width=\"843\" height=\"492\" /><br/> subarray sum depiction\r\n\r\n&nbsp;\r\n\r\n&nbsp;\r\n\r\nJavascript Code below (brute force approach):-\r\n\r\n&nbsp;\r\n\r\n&nbsp;\r\n<div class=\"wp-block-codemirror-blocks code-block alignwide\">\r\n<pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:true,&quot;lineWrapping&quot;:true,&quot;styleActiveLine&quot;:true,&quot;readOnly&quot;:false,&quot;align&quot;:&quot;wide&quot;}\">&lt;script&gt;\r\nfunction max_sub_array_of_size_k(k, arr) {\r\n  let maxSum = 0,\r\n    windowSum = 0;\r\n  // loop through start till array length - k\r\n  for (i = 0; i &lt; arr.length - k + 1; i++) {\r\n    windowSum = 0;\r\n    // loop through i to i + k elements\r\n    for (j = i; j &lt; i + k; j++) {\r\n      windowSum += arr[j];\r\n    }\r\n    maxSum = Math.max(maxSum, windowSum);\r\n  }\r\n  return maxSum;\r\n}\r\n\r\n\r\ndocument.write(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(3, [2, 1, 5, 1, 3, 2])}&lt;br/&gt;`);\r\ndocument.write(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(2, [2, 3, 4, 1, 5])}&lt;br/&gt;`);\r\n&lt;/script&gt;\r\n</pre>\r\n</div>\r\n&nbsp;\r\n\r\n&nbsp;\r\n\r\nThe time complexity of the above algorithm will be <strong>O(N*K)</strong>, where <strong>‘N’</strong> is the total number of elements in the given array and K is the size of sub-array.\r\n\r\nThe above solution works but isn't efficient for large data sets. It will fail and run out of time. We need a better solution.\r\n\r\nTo solve such problems, we use a pattern called <strong>\"sliding window pattern or mechanism\"</strong>\r\n\r\n&nbsp;\r\n\r\n&nbsp;\r\n<h4 id=\"a-better-approach\" data-id=\"2cdf66315d2c2a56f4edd8ce9be179bb\">Sliding window mechanism</h4>\r\n&nbsp;\r\n<p data-id=\"581101dc38b16279e9eb58f9eaa3e0d8\">If we observe closely, we realize that we can reuse the sum of previous sub-array at each point to calculate the sum of current sub-array a.k.a <strong>window</strong>. We consider each sub-array as a <strong>Sliding Window</strong> of size <strong>‘k’</strong>. To calculate the sum of the next sub-array, we need to slide the window ahead by one element. So to slide the window forward and calculate the sum of the new position of the sliding window, we need to do two things:</p>\r\n\r\n<ol data-id=\"27b891f85213769fc57d13aac390468a\">\r\n <li>Subtract the element going out of the sliding window i.e., subtract the first element of the window.</li>\r\n <li>Add the new element getting included in the sliding window i.e., the element coming right after the end of the window.</li>\r\n</ol>\r\n&nbsp;\r\n<p data-id=\"b67a035c1779640e66cb49bfb45dce88\">This approach will save us from re-calculating the sum of the overlapping part of the sliding window. Here is what our algorithm will look like:</p>\r\n\r\n<div class=\"wp-block-codemirror-blocks code-block alignwide\">\r\n<pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:true,&quot;lineWrapping&quot;:true,&quot;styleActiveLine&quot;:true,&quot;readOnly&quot;:false,&quot;align&quot;:&quot;wide&quot;}\">&lt;script&gt;\r\nfunction max_sub_array_of_size_k(k, arr) {\r\nvar maxSum = 0;\r\nvar windowStart = 0;\r\n\r\nvar windowSum = 0;\r\n\r\n\r\nfor (var windowEnd = 0; windowEnd &lt; arr.length; windowEnd++) {\r\nwindowSum += arr[windowEnd];\r\n\r\nif (windowEnd &gt;= k - 1) {\r\nmaxSum = Math.max(maxSum, windowSum);\r\nwindowSum -= arr[windowStart];\r\nwindowStart++;\r\n}\r\n}\r\n\r\nreturn maxSum;\r\n}\r\n\r\n\r\ndocument.write(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(3, [2, 1, 5, 1, 3, 2])}&lt;br/&gt;`);\r\ndocument.write(`Maximum sum of a subarray of size KL ${max_sub_array_of_size_k(2, [2, 3, 4, 1, 5])}&lt;br/&gt;`);\r\n&lt;/script&gt;</pre>\r\n</div>\r\n<h4 data-id=\"4aee6881c21420310492cbdf7cb9003b\"></h4>\r\n&nbsp;\r\n<h4 id=\"time-complexity\" data-id=\"4aee6881c21420310492cbdf7cb9003b\">Time Complexity </h4>\r\n<p data-id=\"f9c90e2b944bd92ebc0b1c2fccda303e\">The time complexity of the above algorithm will be O(N).</p>\r\n<p data-id=\"f9c90e2b944bd92ebc0b1c2fccda303e\"></p>\r\n<p data-id=\"f9c90e2b944bd92ebc0b1c2fccda303e\"></p>\r\n\r\n<h4 id=\"space-complexity\" data-id=\"4557d9eda0cfe746575b79994109e4b8\">Space Complexity </h4>\r\n<p data-id=\"31c0baa71fdd532a3e7bbd7007cac80b\">The algorithm runs in constant space O(1).</p>\r\n&nbsp;\r\n\r\n&nbsp; <br /><center><hr/><em>Posted from my blog with <a href='https://wordpress.org/plugins/steempress/'>SteemPress</a> : https://www.golibrary.co/finding-maximum-size-subarray-with-sum-k-in-a-given-array/ </em><hr/></center> ",
      "json_metadata": "{\"community\":\"steempress\",\"app\":\"steempress\",\"image\":[\"https://www.golibrary.co/wp-content/uploads/2020/03/subarray-sum.png\"],\"tags\":[\"steempress\",\"steem\",\"golibrary\",\"technology\",\"maximum\"],\"canonical_url\":\"https://www.golibrary.co/finding-maximum-size-subarray-with-sum-k-in-a-given-array/\"}"
    }
  ]
}
2020/03/17 11:53:30
votertonimontana
authorgolibrary
permlinkfindingmaximumsizesubarraywithsumkinagivenarray-l9bvm7k1ra
weight726 (7.26%)
Transaction InfoBlock #41729958/Trx 1dd737cf515a7f3addb445e4c26d5497682497e9
View Raw JSON Data
{
  "trx_id": "1dd737cf515a7f3addb445e4c26d5497682497e9",
  "block": 41729958,
  "trx_in_block": 12,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-17T11:53:30",
  "op": [
    "vote",
    {
      "voter": "tonimontana",
      "author": "golibrary",
      "permlink": "findingmaximumsizesubarraywithsumkinagivenarray-l9bvm7k1ra",
      "weight": 726
    }
  ]
}
2020/03/17 11:53:27
authorgolibrary
permlinkfindingmaximumsizesubarraywithsumkinagivenarray-l9bvm7k1ra
max accepted payout1000000.000 SBD
percent steem dollars10000
allow votestrue
allow curation rewardstrue
extensions[[0,{"beneficiaries":[{"account":"steempress","weight":1500}]}]]
Transaction InfoBlock #41729957/Trx 21de361c1150d24af1db059cc85a7f50eadb7f49
View Raw JSON Data
{
  "trx_id": "21de361c1150d24af1db059cc85a7f50eadb7f49",
  "block": 41729957,
  "trx_in_block": 22,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-17T11:53:27",
  "op": [
    "comment_options",
    {
      "author": "golibrary",
      "permlink": "findingmaximumsizesubarraywithsumkinagivenarray-l9bvm7k1ra",
      "max_accepted_payout": "1000000.000 SBD",
      "percent_steem_dollars": 10000,
      "allow_votes": true,
      "allow_curation_rewards": true,
      "extensions": [
        [
          0,
          {
            "beneficiaries": [
              {
                "account": "steempress",
                "weight": 1500
              }
            ]
          }
        ]
      ]
    }
  ]
}
2020/03/17 11:53:27
parent author
parent permlinksteempress
authorgolibrary
permlinkfindingmaximumsizesubarraywithsumkinagivenarray-l9bvm7k1ra
titleFinding maximum size subarray with sum K in a given array
body<center>https://www.golibrary.co/wp-content/uploads/2020/03/subarray-sum.png</center> <br/><h3 id="problem-statement" data-id="0f3c185023ec811f417e671bc39b2ae2">Problem Statement</h3> <p data-id="53407cb1d103ecabf6f1785cf8c7554a">Given an array of positive numbers and a positive number ‘k’, find the <strong>maximum sum of any contiguous subarray of size ‘k’</strong>.</p> <p data-id="53407cb1d103ecabf6f1785cf8c7554a"></p> <p data-id="0b7b29d7656d8d29ec3286a241de010e"><strong>Example 1:</strong></p> Input: [2, 1, 5, 1, 3, 2], k=3  Output: 9 Explanation: Subarray with maximum sum is [5, 1, 3]. <p data-id="0b7b29d7656d8d29ec3286a241de010e"></p> <p data-id="0b7b29d7656d8d29ec3286a241de010e"><strong>Example 2:</strong></p> Input: [2, 3, 4, 1, 5], k=2  Output: 7 Explanation: Subarray with maximum sum is [3, 4]. <h3 id="try-it-yourself" data-id="091e53f55f3812664765f2ff8f3aff6d"></h3> &nbsp; <h3 id="solution" data-id="f69ad95ba722a9debe3d34a9dec8f95b">Solution</h3> A basic brute force solution will be to calculate the sum of all <strong>‘k’</strong> sized subarrays of the given array, to find the subarray with the highest sum. We can start from every index of the given array and add the next <strong>‘k’</strong> elements to find the sum of the subarray. Following is the visual representation of this algorithm for Example-1: &nbsp; <img class="size-full wp-image-2998" src="https://www.golibrary.co/wp-content/uploads/2020/03/subarray-sum.png" alt="subarray sum" width="843" height="492" /><br/> subarray sum depiction &nbsp; &nbsp; Javascript Code below (brute force approach):- &nbsp; &nbsp; <div class="wp-block-codemirror-blocks code-block alignwide"> <pre class="CodeMirror" data-setting="{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:true,&quot;lineWrapping&quot;:true,&quot;styleActiveLine&quot;:true,&quot;readOnly&quot;:false,&quot;align&quot;:&quot;wide&quot;}">&lt;script&gt; function max_sub_array_of_size_k(k, arr) { let maxSum = 0, windowSum = 0; // loop through start till array length - k for (i = 0; i &lt; arr.length - k + 1; i++) { windowSum = 0; // loop through i to i + k elements for (j = i; j &lt; i + k; j++) { windowSum += arr[j]; } maxSum = Math.max(maxSum, windowSum); } return maxSum; } document.write(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(3, [2, 1, 5, 1, 3, 2])}&lt;br/&gt;`); document.write(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(2, [2, 3, 4, 1, 5])}&lt;br/&gt;`); &lt;/script&gt; </pre> </div> &nbsp; &nbsp; The time complexity of the above algorithm will be <strong>O(N*K)</strong>, where <strong>‘N’</strong> is the total number of elements in the given array and K is the size of sub-array. The above solution works but isn't efficient for large data sets. It will fail and run out of time. We need a better solution. To solve such problems, we use a pattern called <strong>"sliding window pattern or mechanism"</strong> &nbsp; <h4 id="a-better-approach" data-id="2cdf66315d2c2a56f4edd8ce9be179bb">Sliding window mechanism</h4> &nbsp; <p data-id="581101dc38b16279e9eb58f9eaa3e0d8">If we observe closely, we realize that we can reuse the sum of previous sub-array at each point to calculate the sum of current sub-array a.k.a <strong>window</strong>. We consider each sub-array as a <strong>Sliding Window</strong> of size <strong>‘k’</strong>. To calculate the sum of the next sub-array, we need to slide the window ahead by one element. So to slide the window forward and calculate the sum of the new position of the sliding window, we need to do two things:</p> <ol data-id="27b891f85213769fc57d13aac390468a"> <li>Subtract the element going out of the sliding window i.e., subtract the first element of the window.</li> <li>Add the new element getting included in the sliding window i.e., the element coming right after the end of the window.</li> </ol> &nbsp; <p data-id="b67a035c1779640e66cb49bfb45dce88">This approach will save us from re-calculating the sum of the overlapping part of the sliding window. Here is what our algorithm will look like:</p> <div class="wp-block-codemirror-blocks code-block alignwide"> <pre class="CodeMirror" data-setting="{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:true,&quot;lineWrapping&quot;:true,&quot;styleActiveLine&quot;:true,&quot;readOnly&quot;:false,&quot;align&quot;:&quot;wide&quot;}">&lt;script&gt; function max_sub_array_of_size_k(k, arr) { var maxSum = 0; var windowStart = 0; var windowSum = 0; for (var windowEnd = 0; windowEnd &lt; arr.length; windowEnd++) { windowSum += arr[windowEnd]; if (windowEnd &gt;= k - 1) { maxSum = Math.max(maxSum, windowSum); windowSum -= arr[windowStart]; windowStart++; } } return maxSum; } document.write(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(3, [2, 1, 5, 1, 3, 2])}&lt;br/&gt;`); document.write(`Maximum sum of a subarray of size KL ${max_sub_array_of_size_k(2, [2, 3, 4, 1, 5])}&lt;br/&gt;`); &lt;/script&gt;</pre> </div> <h4 data-id="4aee6881c21420310492cbdf7cb9003b"></h4> &nbsp; <h4 id="time-complexity" data-id="4aee6881c21420310492cbdf7cb9003b">Time Complexity </h4> <p data-id="f9c90e2b944bd92ebc0b1c2fccda303e">The time complexity of the above algorithm will be O(N).</p> <p data-id="f9c90e2b944bd92ebc0b1c2fccda303e"></p> <h4 id="space-complexity" data-id="4557d9eda0cfe746575b79994109e4b8">Space Complexity </h4> <p data-id="31c0baa71fdd532a3e7bbd7007cac80b">The algorithm runs in constant space O(1).</p> <p data-id="31c0baa71fdd532a3e7bbd7007cac80b"></p> <p data-id="31c0baa71fdd532a3e7bbd7007cac80b"></p> &nbsp; &nbsp; <br /><center><hr/><em>Posted from my blog with <a href='https://wordpress.org/plugins/steempress/'>SteemPress</a> : https://www.golibrary.co/finding-maximum-size-subarray-with-sum-k-in-a-given-array/ </em><hr/></center>
json metadata{"community":"steempress","app":"steempress","image":["https://www.golibrary.co/wp-content/uploads/2020/03/subarray-sum.png"],"tags":["steempress","steem","golibrary","technology","maximum"],"canonical_url":"https://www.golibrary.co/finding-maximum-size-subarray-with-sum-k-in-a-given-array/"}
Transaction InfoBlock #41729957/Trx 21de361c1150d24af1db059cc85a7f50eadb7f49
View Raw JSON Data
{
  "trx_id": "21de361c1150d24af1db059cc85a7f50eadb7f49",
  "block": 41729957,
  "trx_in_block": 22,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-17T11:53:27",
  "op": [
    "comment",
    {
      "parent_author": "",
      "parent_permlink": "steempress",
      "author": "golibrary",
      "permlink": "findingmaximumsizesubarraywithsumkinagivenarray-l9bvm7k1ra",
      "title": "Finding maximum size subarray with sum K in a given array",
      "body": "<center>https://www.golibrary.co/wp-content/uploads/2020/03/subarray-sum.png</center> <br/><h3 id=\"problem-statement\" data-id=\"0f3c185023ec811f417e671bc39b2ae2\">Problem Statement</h3>\r\n<p data-id=\"53407cb1d103ecabf6f1785cf8c7554a\">Given an array of positive numbers and a positive number ‘k’, find the <strong>maximum sum of any contiguous subarray of size ‘k’</strong>.</p>\r\n<p data-id=\"53407cb1d103ecabf6f1785cf8c7554a\"></p>\r\n<p data-id=\"0b7b29d7656d8d29ec3286a241de010e\"><strong>Example 1:</strong></p>\r\nInput: [2, 1, 5, 1, 3, 2], k=3 \r\n\r\nOutput: 9\r\n\r\nExplanation: Subarray with maximum sum is [5, 1, 3].\r\n<p data-id=\"0b7b29d7656d8d29ec3286a241de010e\"></p>\r\n<p data-id=\"0b7b29d7656d8d29ec3286a241de010e\"><strong>Example 2:</strong></p>\r\nInput: [2, 3, 4, 1, 5], k=2 \r\n\r\nOutput: 7\r\n\r\nExplanation: Subarray with maximum sum is [3, 4].\r\n<h3 id=\"try-it-yourself\" data-id=\"091e53f55f3812664765f2ff8f3aff6d\"></h3>\r\n&nbsp;\r\n<h3 id=\"solution\" data-id=\"f69ad95ba722a9debe3d34a9dec8f95b\">Solution</h3>\r\nA basic brute force solution will be to calculate the sum of all <strong>‘k’</strong> sized subarrays of the given array, to find the subarray with the highest sum. We can start from every index of the given array and add the next <strong>‘k’</strong> elements to find the sum of the subarray. Following is the visual representation of this algorithm for Example-1:\r\n\r\n&nbsp;\r\n\r <img class=\"size-full wp-image-2998\" src=\"https://www.golibrary.co/wp-content/uploads/2020/03/subarray-sum.png\" alt=\"subarray sum\" width=\"843\" height=\"492\" /><br/> subarray sum depiction\r\n\r\n&nbsp;\r\n\r\n&nbsp;\r\n\r\nJavascript Code below (brute force approach):-\r\n\r\n&nbsp;\r\n\r\n&nbsp;\r\n<div class=\"wp-block-codemirror-blocks code-block alignwide\">\r\n<pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:true,&quot;lineWrapping&quot;:true,&quot;styleActiveLine&quot;:true,&quot;readOnly&quot;:false,&quot;align&quot;:&quot;wide&quot;}\">&lt;script&gt;\r\nfunction max_sub_array_of_size_k(k, arr) {\r\n  let maxSum = 0,\r\n    windowSum = 0;\r\n  // loop through start till array length - k\r\n  for (i = 0; i &lt; arr.length - k + 1; i++) {\r\n    windowSum = 0;\r\n    // loop through i to i + k elements\r\n    for (j = i; j &lt; i + k; j++) {\r\n      windowSum += arr[j];\r\n    }\r\n    maxSum = Math.max(maxSum, windowSum);\r\n  }\r\n  return maxSum;\r\n}\r\n\r\n\r\ndocument.write(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(3, [2, 1, 5, 1, 3, 2])}&lt;br/&gt;`);\r\ndocument.write(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(2, [2, 3, 4, 1, 5])}&lt;br/&gt;`);\r\n&lt;/script&gt;\r\n</pre>\r\n</div>\r\n&nbsp;\r\n\r\n&nbsp;\r\n\r\nThe time complexity of the above algorithm will be <strong>O(N*K)</strong>, where <strong>‘N’</strong> is the total number of elements in the given array and K is the size of sub-array.\r\n\r\nThe above solution works but isn't efficient for large data sets. It will fail and run out of time. We need a better solution.\r\n\r\nTo solve such problems, we use a pattern called <strong>\"sliding window pattern or mechanism\"</strong>\r\n\r\n&nbsp;\r\n<h4 id=\"a-better-approach\" data-id=\"2cdf66315d2c2a56f4edd8ce9be179bb\">Sliding window mechanism</h4>\r\n&nbsp;\r\n<p data-id=\"581101dc38b16279e9eb58f9eaa3e0d8\">If we observe closely, we realize that we can reuse the sum of previous sub-array at each point to calculate the sum of current sub-array a.k.a <strong>window</strong>. We consider each sub-array as a <strong>Sliding Window</strong> of size <strong>‘k’</strong>. To calculate the sum of the next sub-array, we need to slide the window ahead by one element. So to slide the window forward and calculate the sum of the new position of the sliding window, we need to do two things:</p>\r\n\r\n<ol data-id=\"27b891f85213769fc57d13aac390468a\">\r\n <li>Subtract the element going out of the sliding window i.e., subtract the first element of the window.</li>\r\n <li>Add the new element getting included in the sliding window i.e., the element coming right after the end of the window.</li>\r\n</ol>\r\n&nbsp;\r\n<p data-id=\"b67a035c1779640e66cb49bfb45dce88\">This approach will save us from re-calculating the sum of the overlapping part of the sliding window. Here is what our algorithm will look like:</p>\r\n\r\n<div class=\"wp-block-codemirror-blocks code-block alignwide\">\r\n<pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:true,&quot;lineWrapping&quot;:true,&quot;styleActiveLine&quot;:true,&quot;readOnly&quot;:false,&quot;align&quot;:&quot;wide&quot;}\">&lt;script&gt;\r\nfunction max_sub_array_of_size_k(k, arr) {\r\nvar maxSum = 0;\r\nvar windowStart = 0;\r\n\r\nvar windowSum = 0;\r\n\r\n\r\nfor (var windowEnd = 0; windowEnd &lt; arr.length; windowEnd++) {\r\nwindowSum += arr[windowEnd];\r\n\r\nif (windowEnd &gt;= k - 1) {\r\nmaxSum = Math.max(maxSum, windowSum);\r\nwindowSum -= arr[windowStart];\r\nwindowStart++;\r\n}\r\n}\r\n\r\nreturn maxSum;\r\n}\r\n\r\n\r\ndocument.write(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(3, [2, 1, 5, 1, 3, 2])}&lt;br/&gt;`);\r\ndocument.write(`Maximum sum of a subarray of size KL ${max_sub_array_of_size_k(2, [2, 3, 4, 1, 5])}&lt;br/&gt;`);\r\n&lt;/script&gt;</pre>\r\n</div>\r\n<h4 data-id=\"4aee6881c21420310492cbdf7cb9003b\"></h4>\r\n&nbsp;\r\n<h4 id=\"time-complexity\" data-id=\"4aee6881c21420310492cbdf7cb9003b\">Time Complexity </h4>\r\n<p data-id=\"f9c90e2b944bd92ebc0b1c2fccda303e\">The time complexity of the above algorithm will be O(N).</p>\r\n<p data-id=\"f9c90e2b944bd92ebc0b1c2fccda303e\"></p>\r\n\r\n<h4 id=\"space-complexity\" data-id=\"4557d9eda0cfe746575b79994109e4b8\">Space Complexity </h4>\r\n<p data-id=\"31c0baa71fdd532a3e7bbd7007cac80b\">The algorithm runs in constant space O(1).</p>\r\n<p data-id=\"31c0baa71fdd532a3e7bbd7007cac80b\"></p>\r\n<p data-id=\"31c0baa71fdd532a3e7bbd7007cac80b\"></p>\r\n&nbsp;\r\n\r\n&nbsp; <br /><center><hr/><em>Posted from my blog with <a href='https://wordpress.org/plugins/steempress/'>SteemPress</a> : https://www.golibrary.co/finding-maximum-size-subarray-with-sum-k-in-a-given-array/ </em><hr/></center> ",
      "json_metadata": "{\"community\":\"steempress\",\"app\":\"steempress\",\"image\":[\"https://www.golibrary.co/wp-content/uploads/2020/03/subarray-sum.png\"],\"tags\":[\"steempress\",\"steem\",\"golibrary\",\"technology\",\"maximum\"],\"canonical_url\":\"https://www.golibrary.co/finding-maximum-size-subarray-with-sum-k-in-a-given-array/\"}"
    }
  ]
}
2020/03/09 17:50:00
voterabh12345.stem
authorgolibrary
permlinkhistoryofunixandlinux-mhf7yno5g3
weight-500 (-5.00%)
Transaction InfoBlock #41507090/Trx 460cba975b5160b1048de59e02cc808d5a655d99
View Raw JSON Data
{
  "trx_id": "460cba975b5160b1048de59e02cc808d5a655d99",
  "block": 41507090,
  "trx_in_block": 15,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-09T17:50:00",
  "op": [
    "vote",
    {
      "voter": "abh12345.stem",
      "author": "golibrary",
      "permlink": "historyofunixandlinux-mhf7yno5g3",
      "weight": -500
    }
  ]
}
2020/03/09 11:32:33
voterfilipino
authorgolibrary
permlinkhistoryofunixandlinux-mhf7yno5g3
weight1000 (10.00%)
Transaction InfoBlock #41499556/Trx 2d33a3b46ea2b5cd6e67f8334057947c69b8bc41
View Raw JSON Data
{
  "trx_id": "2d33a3b46ea2b5cd6e67f8334057947c69b8bc41",
  "block": 41499556,
  "trx_in_block": 5,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-09T11:32:33",
  "op": [
    "vote",
    {
      "voter": "filipino",
      "author": "golibrary",
      "permlink": "historyofunixandlinux-mhf7yno5g3",
      "weight": 1000
    }
  ]
}
2020/03/09 11:16:45
authorgolibrary
permlinkpuppetbasicconcepts-p01w0ihq9c
max accepted payout1000000.000 SBD
percent steem dollars10000
allow votestrue
allow curation rewardstrue
extensions[[0,{"beneficiaries":[{"account":"steempress","weight":1500}]}]]
Transaction InfoBlock #41499241/Trx ad94cb621b995f6ac300d45c673c3b465f1ae44d
View Raw JSON Data
{
  "trx_id": "ad94cb621b995f6ac300d45c673c3b465f1ae44d",
  "block": 41499241,
  "trx_in_block": 10,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-09T11:16:45",
  "op": [
    "comment_options",
    {
      "author": "golibrary",
      "permlink": "puppetbasicconcepts-p01w0ihq9c",
      "max_accepted_payout": "1000000.000 SBD",
      "percent_steem_dollars": 10000,
      "allow_votes": true,
      "allow_curation_rewards": true,
      "extensions": [
        [
          0,
          {
            "beneficiaries": [
              {
                "account": "steempress",
                "weight": 1500
              }
            ]
          }
        ]
      ]
    }
  ]
}
2020/03/09 11:16:45
parent author
parent permlinksteempress
authorgolibrary
permlinkpuppetbasicconcepts-p01w0ihq9c
titlePuppet Basic Concepts
body<center>https://www.golibrary.co/wp-content/uploads/2020/03/puppet-basics.jpg</center> <br/><div class="entry-content"> <strong>What is Puppet?</strong> <ul> <li>Puppet is an open-source configuration management tool.</li> <li>It is a declarative language for expressing system  configuration.</li> <li>Puppet is a client and server for distributing it.</li> <li>It is a library for realizing the configuration.</li> <li>Puppet is written in ruby and distributed under the GPL.</li> <li>Puppet is made by Luke Kanies.</li> <li>Currently puppet is supported by Puppet Labs(Luke Kanies is the CEO of Puppet Labs)</li> <li>Puppet code is written in manifests (files with .pp extension)</li> <li>In the code we declare resources that affect elements of the system (files, packages, services …)</li> <li>Resources are grouped in classes which may expose parameters that affect their behavior.</li> <li>Classes and configuration files are organized in modules.</li> <li>Configuration Management Advantage : Infrastructure as Code: Track, Test, Deploy, Reproduce, Scale.</li> <li>Alternatives to Puppet: Chef, CFEngine, Salt, Ansible</li> </ul> &nbsp; <img class="wp-image-2949 size-full" src="https://www.golibrary.co/wp-content/uploads/2020/03/puppet-new-logo-1.jpg" alt="Puppet basic concepts" width="770" height="330" /><br/> Puppet basic concepts </div> &nbsp; &nbsp; <div class="entry-content"> <strong>How Puppet Works ?</strong> Server : puppetmasterd Client : puppetd &nbsp; <ul> <li>The connection between puppet agent and master is made in a secure encrypted channel with the help of SSL.</li> <li>The cleint connects to the server every 30minutes.</li> <li>The server compiles the configuration for the client, and compiles it and make it a catalog and sends it to the cleint.This catalog is given to the puppet agent of the node.</li> <li>The client checks the configuration it receives against what is really on the machine and tries to fix whatever is wrong.</li> <li>Node(cleint) configuration can be stored in LDAP, in a database or in the puppet configuration files.<strong>What Puppet Needs?</strong></li> <li>ruby</li> <li>facter</li> <li>puppet<strong>Facter :</strong> Facter is a system profiling tool. It collects a plethora of system information like operating system, network interfaces, uptime, and so much more. Facter’s facts can be used when writing Puppet code so your code can always do the right thing without any investigative logic required.<strong>Puppet terminology and concepts :</strong><strong>Resources :</strong> Puppet ships with a number of pre-defined resources, which are the fundamental components of your infrastructure. The most commonly used resource types are files, users, packages and services. You can see a complete list of built-in resource types here. Puppet revolves around the management of these resources. Let’s say, for example, we need to ensure that the ssh service is always up and running. The code below does this.service   <div class="wp-block-codemirror-blocks code-block "> <pre class="CodeMirror" data-setting="{&quot;mode&quot;:&quot;shell&quot;,&quot;mime&quot;:&quot;text/x-sh&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:true,&quot;lineWrapping&quot;:true,&quot;styleActiveLine&quot;:true,&quot;readOnly&quot;:false,&quot;align&quot;:&quot;&quot;}">{ ‘ ssh’: ensure =&gt; running, }</pre> </div></li> </ul> </div> &nbsp; <div class="entry-content"> <strong>Manifests</strong> Manifest are recipes that Puppet users to build the client configuration. Manifests are the files that contain Puppet code. These files end with a .pp file extension. So if we wanted to save this ssh resource definition, we would save it in a manifest. <em><strong>/etc/puppet/manifests/site.pp.</strong></em> &nbsp; <em><strong>example :</strong></em> &nbsp; <div class="wp-block-codemirror-blocks code-block "> <pre class="CodeMirror" data-setting="{&quot;mode&quot;:&quot;shell&quot;,&quot;mime&quot;:&quot;text/x-sh&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:true,&quot;lineWrapping&quot;:true,&quot;styleActiveLine&quot;:true,&quot;readOnly&quot;:false,&quot;align&quot;:&quot;&quot;}">class bacula - client {} node server - db { include bacula - client }</pre> </div> </div> &nbsp; <div class="entry-content"> <strong>Classes</strong> When we create a class, it’s really a set of configurations wrapped together — resources, variables and more advanced attributes. Anytime we assign this class to a machine, it will get those configurations. Here’s what the class definition looks like: &nbsp; <div class="wp-block-codemirror-blocks code-block "> <pre class="CodeMirror" data-setting="{&quot;mode&quot;:&quot;shell&quot;,&quot;mime&quot;:&quot;text/x-sh&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:true,&quot;lineWrapping&quot;:true,&quot;styleActiveLine&quot;:true,&quot;readOnly&quot;:false,&quot;align&quot;:&quot;&quot;}">class openssh { package { ‘ openssh - server’: ensure =&gt; installed, } file { ‘ /etc/ssh / sshd_config’: ensure =&gt; file, owner =&gt; ‘root’, mode =&gt; ‘0600’, } service { ‘ ssh’: ensure =&gt; running, } }</pre> </div> &nbsp; &nbsp; &nbsp; This code wraps the resource declaration in a class, so that the puppet master can apply it to any node assigned that class. It doesn’t matter how many nodes are assigned to a class — it could be one, or one hundred. &nbsp; <strong>Modules:</strong> Puppet modules allow you to share the Puppet code that you or someone else has written to manage a piece of your infrastructure. If there is something that you want to manage with Puppet, there is probably a module for it on the Puppet Forge, which includes community-contributed modules, as well as those written by Puppet Labs employees. You’ll also find a list of Puppet Enterprise Supported Modules, which are written and tested by Puppet Labs employees. This list is constantly growing. &nbsp; <strong>What is a Puppet module?</strong> It’s really just a collection of files and directories that can contain Puppet manifests, as well as other objects such as files and templates, all packaged and organized in a way that Puppet can understand and use. When you download a module from the Forge, you are downloading a top-level directory with several sub-directories that contain the components needed to specify the desired state. When you want to use that module to manage your nodes, you classify each node by assigning to it a class within the module. Now let’s put all these pieces together: Resources can be contained within classes. Classes can live in a manifest. Manifests can live in a module. &nbsp; <strong>Catalog</strong> In order for the nodes in your environment to interpret the classes that have been assigned to them, Puppet compiles a catalog. The catalog describes the resources that need to managed, specifying the states those resources should be in, so each node can configure itself based on those definitions. Once the catalog is applied, the Puppet agent produces a report showing which resources were managed, and any changes that were needed to move into your desired state. &nbsp; <strong>What are the Software  related to Puppet ?</strong> <ul> <li>Facter – Complementary tool to retrieve system’s data</li> <li>MCollective – Infrastructure Orchestration framework</li> <li>Hiera – Key-value lookup tool where Puppet data can be placed</li> <li>PuppetDB – Stores all the data generated by Puppet</li> <li>Puppet DashBoard – A Puppet Web frontend and External Node Classifier (ENC)</li> <li>The Foreman – A well-known third party provisioning tool and Puppet ENC</li> <li>Geppetto – A Puppet IDE based on Eclipse</li> </ul> </div> &nbsp; &nbsp; <br /><center><hr/><em>Posted from my blog with <a href='https://wordpress.org/plugins/steempress/'>SteemPress</a> : https://www.golibrary.co/puppet-basic-concepts/ </em><hr/></center>
json metadata{"community":"steempress","app":"steempress","image":["https://www.golibrary.co/wp-content/uploads/2020/03/puppet-basics.jpg"],"tags":["steempress","steem","golibrary","technology"],"canonical_url":"https://www.golibrary.co/puppet-basic-concepts/"}
Transaction InfoBlock #41499241/Trx ad94cb621b995f6ac300d45c673c3b465f1ae44d
View Raw JSON Data
{
  "trx_id": "ad94cb621b995f6ac300d45c673c3b465f1ae44d",
  "block": 41499241,
  "trx_in_block": 10,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-09T11:16:45",
  "op": [
    "comment",
    {
      "parent_author": "",
      "parent_permlink": "steempress",
      "author": "golibrary",
      "permlink": "puppetbasicconcepts-p01w0ihq9c",
      "title": "Puppet Basic Concepts",
      "body": "<center>https://www.golibrary.co/wp-content/uploads/2020/03/puppet-basics.jpg</center> <br/><div class=\"entry-content\">\r\n\r\n<strong>What is Puppet?</strong>\r\n<ul>\r\n <li>Puppet is an open-source configuration management tool.</li>\r\n <li>It is a declarative language for expressing system  configuration.</li>\r\n <li>Puppet is a client and server for distributing it.</li>\r\n <li>It is a library for realizing the configuration.</li>\r\n <li>Puppet is written in ruby and distributed under the GPL.</li>\r\n <li>Puppet is made by Luke Kanies.</li>\r\n <li>Currently puppet is supported by Puppet Labs(Luke Kanies is the CEO of Puppet Labs)</li>\r\n <li>Puppet code is written in manifests (files with .pp extension)</li>\r\n <li>In the code we declare resources that affect elements of the system (files, packages, services …)</li>\r\n <li>Resources are grouped in classes which may expose parameters that affect their behavior.</li>\r\n <li>Classes and configuration files are organized in modules.</li>\r\n <li>Configuration Management Advantage : Infrastructure as Code: Track, Test, Deploy, Reproduce, Scale.</li>\r\n <li>Alternatives to Puppet: Chef, CFEngine, Salt, Ansible</li>\r\n</ul>\r\n&nbsp;\r\n\r <img class=\"wp-image-2949 size-full\" src=\"https://www.golibrary.co/wp-content/uploads/2020/03/puppet-new-logo-1.jpg\" alt=\"Puppet basic concepts\" width=\"770\" height=\"330\" /><br/> Puppet basic concepts\r\n\r\n</div>\r\n&nbsp;\r\n\r\n&nbsp;\r\n<div class=\"entry-content\">\r\n\r\n<strong>How Puppet Works ?</strong>\r\n\r\nServer : puppetmasterd\r\nClient : puppetd\r\n\r\n&nbsp;\r\n<ul>\r\n <li>The connection between puppet agent and master is made in a secure encrypted channel with the help of SSL.</li>\r\n <li>The cleint connects to the server every 30minutes.</li>\r\n <li>The server compiles the configuration for the client, and compiles it and make it a catalog and sends it to the cleint.This catalog is given to the puppet agent of the node.</li>\r\n <li>The client checks the configuration it receives against what is really on the machine and tries to fix whatever is wrong.</li>\r\n <li>Node(cleint) configuration can be stored in LDAP, in a database or in the puppet configuration files.<strong>What Puppet Needs?</strong></li>\r\n <li>ruby</li>\r\n <li>facter</li>\r\n <li>puppet<strong>Facter :</strong> Facter is a system profiling tool. It collects a plethora of system information like operating system, network interfaces, uptime, and so much more. Facter’s facts can be used when writing Puppet code so your code can always do the right thing without any investigative logic required.<strong>Puppet terminology and concepts :</strong><strong>Resources :</strong>\r\nPuppet ships with a number of pre-defined resources, which are the fundamental components of your infrastructure. The most commonly used resource types are files, users, packages and services. You can see a complete list of built-in resource types here.\r\nPuppet revolves around the management of these resources. Let’s say, for example, we need to ensure that the ssh service is always up and running. The code below does this.service  \r\n<div class=\"wp-block-codemirror-blocks code-block \">\r\n<pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;shell&quot;,&quot;mime&quot;:&quot;text/x-sh&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:true,&quot;lineWrapping&quot;:true,&quot;styleActiveLine&quot;:true,&quot;readOnly&quot;:false,&quot;align&quot;:&quot;&quot;}\">{\r\n  ‘\r\n  ssh’: ensure =&gt; running,\r\n}</pre>\r\n</div></li>\r\n</ul>\r\n</div>\r\n&nbsp;\r\n<div class=\"entry-content\">\r\n\r\n<strong>Manifests</strong>\r\n\r\nManifest are recipes that Puppet users to build the client configuration.\r\nManifests are the files that contain Puppet code. These files end with a .pp file extension. So if we wanted to save this ssh resource definition, we would save it in a manifest.\r\n<em><strong>/etc/puppet/manifests/site.pp.</strong></em>\r\n\r\n&nbsp;\r\n\r\n<em><strong>example :</strong></em>\r\n\r\n&nbsp;\r\n<div class=\"wp-block-codemirror-blocks code-block \">\r\n<pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;shell&quot;,&quot;mime&quot;:&quot;text/x-sh&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:true,&quot;lineWrapping&quot;:true,&quot;styleActiveLine&quot;:true,&quot;readOnly&quot;:false,&quot;align&quot;:&quot;&quot;}\">class bacula - client {}\r\nnode server - db {\r\n  include bacula - client\r\n}</pre>\r\n</div>\r\n</div>\r\n&nbsp;\r\n<div class=\"entry-content\">\r\n\r\n<strong>Classes</strong>\r\n\r\nWhen we create a class, it’s really a set of configurations wrapped together — resources, variables and more advanced attributes. Anytime we assign this class to a machine, it will get those configurations. Here’s what the class definition looks like:\r\n\r\n&nbsp;\r\n<div class=\"wp-block-codemirror-blocks code-block \">\r\n<pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;shell&quot;,&quot;mime&quot;:&quot;text/x-sh&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:true,&quot;lineWrapping&quot;:true,&quot;styleActiveLine&quot;:true,&quot;readOnly&quot;:false,&quot;align&quot;:&quot;&quot;}\">class openssh {\r\n  package {\r\n    ‘\r\n    openssh - server’:\r\n      ensure =&gt; installed,\r\n  }\r\n\r\n  file {\r\n    ‘\r\n    /etc/ssh / sshd_config’:\r\n      ensure =&gt; file,\r\n      owner =&gt; ‘root’,\r\n      mode =&gt; ‘0600’,\r\n  }\r\n\r\n  service {\r\n    ‘\r\n    ssh’: ensure =&gt; running,\r\n  }\r\n}</pre>\r\n</div>\r\n&nbsp;\r\n\r\n&nbsp;\r\n\r\n&nbsp;\r\n\r\nThis code wraps the resource declaration in a class, so that the puppet master can apply it to any node assigned that class. It doesn’t matter how many nodes are assigned to a class — it could be one, or one hundred.\r\n\r\n&nbsp;\r\n\r\n<strong>Modules:</strong>\r\n\r\nPuppet modules allow you to share the Puppet code that you or someone else has written to manage a piece of your infrastructure. If there is something that you want to manage with Puppet, there is probably a module for it on the Puppet Forge, which includes community-contributed modules, as well as those written by Puppet Labs employees. You’ll also find a list of Puppet Enterprise Supported Modules, which are written and tested by Puppet Labs employees. This list is constantly growing.\r\n\r\n&nbsp;\r\n\r\n<strong>What is a Puppet module?</strong>\r\n\r\nIt’s really just a collection of files and directories that can contain Puppet manifests, as well as other objects such as files and templates, all packaged and organized in a way that Puppet can understand and use. When you download a module from the Forge, you are downloading a top-level directory with several sub-directories that contain the components needed to specify the desired state. When you want to use that module to manage your nodes, you classify each node by assigning to it a class within the module.\r\n\r\nNow let’s put all these pieces together:\r\n\r\nResources can be contained within classes.\r\nClasses can live in a manifest.\r\nManifests can live in a module.\r\n\r\n&nbsp;\r\n\r\n<strong>Catalog</strong>\r\n\r\nIn order for the nodes in your environment to interpret the classes that have been assigned to them, Puppet compiles a catalog. The catalog describes the resources that need to managed, specifying the states those resources should be in, so each node can configure itself based on those definitions. Once the catalog is applied, the Puppet agent produces a report showing which resources were managed, and any changes that were needed to move into your desired state.\r\n\r\n&nbsp;\r\n\r\n<strong>What are the Software  related to Puppet ?</strong>\r\n<ul>\r\n <li>Facter – Complementary tool to retrieve system’s data</li>\r\n <li>MCollective – Infrastructure Orchestration framework</li>\r\n <li>Hiera – Key-value lookup tool where Puppet data can be placed</li>\r\n <li>PuppetDB – Stores all the data generated by Puppet</li>\r\n <li>Puppet DashBoard – A Puppet Web frontend and External Node Classifier (ENC)</li>\r\n <li>The Foreman – A well-known third party provisioning tool and Puppet ENC</li>\r\n <li>Geppetto – A Puppet IDE based on Eclipse</li>\r\n</ul>\r\n</div>\r\n&nbsp;\r\n\r\n&nbsp; <br /><center><hr/><em>Posted from my blog with <a href='https://wordpress.org/plugins/steempress/'>SteemPress</a> : https://www.golibrary.co/puppet-basic-concepts/ </em><hr/></center> ",
      "json_metadata": "{\"community\":\"steempress\",\"app\":\"steempress\",\"image\":[\"https://www.golibrary.co/wp-content/uploads/2020/03/puppet-basics.jpg\"],\"tags\":[\"steempress\",\"steem\",\"golibrary\",\"technology\"],\"canonical_url\":\"https://www.golibrary.co/puppet-basic-concepts/\"}"
    }
  ]
}
2020/03/09 11:07:45
voterolaf123
authorgolibrary
permlinkhistoryofunixandlinux-mhf7yno5g3
weight100 (1.00%)
Transaction InfoBlock #41499061/Trx eab64cc046e91f2bd731970fb5bc3a61c42ddb32
View Raw JSON Data
{
  "trx_id": "eab64cc046e91f2bd731970fb5bc3a61c42ddb32",
  "block": 41499061,
  "trx_in_block": 41,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-09T11:07:45",
  "op": [
    "vote",
    {
      "voter": "olaf123",
      "author": "golibrary",
      "permlink": "historyofunixandlinux-mhf7yno5g3",
      "weight": 100
    }
  ]
}
2020/03/09 11:07:45
parent authorgolibrary
parent permlinkhistoryofunixandlinux-mhf7yno5g3
authorolaf123
permlinkuhxvids8x9
title
body ### According to the Bible, *Graven Images: Should You Worship These According to the Bible?* ### Watch the Video below to know the Answer... ***(Sorry for sending this comment. We are not looking for our self profit, our intentions is to preach the words of God in any means possible.)*** https://youtu.be/vJWTMjWmdMQ Comment what you understand of our Youtube Video to receive our full votes. We have 30,000 #SteemPower. It's our little way to **Thank you, our beloved friend.** Check our [Discord Chat](https://discord.gg/vzHFNd6) Join our Official Community: https://steemit.com/created/hive-182074
json metadata
Transaction InfoBlock #41499061/Trx a6356d855242e69c5e435c8522df6a212e57a3a8
View Raw JSON Data
{
  "trx_id": "a6356d855242e69c5e435c8522df6a212e57a3a8",
  "block": 41499061,
  "trx_in_block": 40,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-09T11:07:45",
  "op": [
    "comment",
    {
      "parent_author": "golibrary",
      "parent_permlink": "historyofunixandlinux-mhf7yno5g3",
      "author": "olaf123",
      "permlink": "uhxvids8x9",
      "title": "",
      "body": "\n### According to the Bible, *Graven Images: Should You Worship These According to the Bible?*\n### Watch the Video below to know the Answer...\n***(Sorry for sending this comment. We are not looking for our self profit, our intentions is to preach the words of God in any means possible.)***\nhttps://youtu.be/vJWTMjWmdMQ\nComment what you understand of our Youtube Video to receive our full votes. We have 30,000 #SteemPower. It's our little way to **Thank you, our beloved friend.**  \nCheck our [Discord Chat](https://discord.gg/vzHFNd6) \nJoin our Official Community: https://steemit.com/created/hive-182074\n",
      "json_metadata": ""
    }
  ]
}
2020/03/09 11:05:03
votergolibrary
authorgolibrary
permlinkhistoryofunixandlinux-mhf7yno5g3
weight10000 (100.00%)
Transaction InfoBlock #41499007/Trx 1e34819700159ac172a8ba39a700a2f6b1b07711
View Raw JSON Data
{
  "trx_id": "1e34819700159ac172a8ba39a700a2f6b1b07711",
  "block": 41499007,
  "trx_in_block": 19,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-09T11:05:03",
  "op": [
    "vote",
    {
      "voter": "golibrary",
      "author": "golibrary",
      "permlink": "historyofunixandlinux-mhf7yno5g3",
      "weight": 10000
    }
  ]
}
2020/03/09 11:04:24
voterpartitura.stem
authorgolibrary
permlinkhistoryofunixandlinux-mhf7yno5g3
weight10000 (100.00%)
Transaction InfoBlock #41498994/Trx 634c0065c799343194b979f261b4815763ddf848
View Raw JSON Data
{
  "trx_id": "634c0065c799343194b979f261b4815763ddf848",
  "block": 41498994,
  "trx_in_block": 31,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-09T11:04:24",
  "op": [
    "vote",
    {
      "voter": "partitura.stem",
      "author": "golibrary",
      "permlink": "historyofunixandlinux-mhf7yno5g3",
      "weight": 10000
    }
  ]
}
2020/03/09 11:03:06
voteraafeng
authorgolibrary
permlinkhistoryofunixandlinux-mhf7yno5g3
weight1500 (15.00%)
Transaction InfoBlock #41498969/Trx 0314231986088d024943e5665f6a1879d0ceed84
View Raw JSON Data
{
  "trx_id": "0314231986088d024943e5665f6a1879d0ceed84",
  "block": 41498969,
  "trx_in_block": 15,
  "op_in_trx": 0,
  "virtual_op": 0,
  "timestamp": "2020-03-09T11:03:06",
  "op": [
    "vote",
    {
      "voter": "aafeng",
      "author": "golibrary",
      "permlink": "historyofunixandlinux-mhf7yno5g3",
      "weight": 1500
    }
  ]
}

Account Metadata

POSTING JSON METADATA
None
JSON METADATA
None
{
  "posting_json_metadata": {},
  "json_metadata": {}
}

Auth Keys

Owner
Single Signature
Public Keys
STM8FP7i1oJrYAkUbLzWnvTdt96veEd6enUVG6GW4VhVDyqMwVuK71/1
Active
Single Signature
Public Keys
STM8JhXzxDn1wknU8wfgsUhu2kUh8jJm9Y6NYAGKcY3B3TQ5uhBUJ1/1
Posting
Single Signature
Public Keys
STM7rCjZzdVTP2mtB59XXofgqFxLimUmsEgx56cYvU949CJxGi54g1/1
Memo
STM7GJE6AoQW45SSmqFQh4xinJhz4wk9UJozxW1mto34nrRakVC8Y
{
  "owner": {
    "account_auths": [],
    "key_auths": [
      [
        "STM8FP7i1oJrYAkUbLzWnvTdt96veEd6enUVG6GW4VhVDyqMwVuK7",
        1
      ]
    ],
    "weight_threshold": 1
  },
  "active": {
    "account_auths": [],
    "key_auths": [
      [
        "STM8JhXzxDn1wknU8wfgsUhu2kUh8jJm9Y6NYAGKcY3B3TQ5uhBUJ",
        1
      ]
    ],
    "weight_threshold": 1
  },
  "posting": {
    "account_auths": [],
    "key_auths": [
      [
        "STM7rCjZzdVTP2mtB59XXofgqFxLimUmsEgx56cYvU949CJxGi54g",
        1
      ]
    ],
    "weight_threshold": 1
  },
  "memo": "STM7GJE6AoQW45SSmqFQh4xinJhz4wk9UJozxW1mto34nrRakVC8Y"
}

Witness Votes

0 / 30
No active witness votes.
[]